[clug] Thursday afternoon Perl/bash golf time

Peter Barker pbarker at barker.dropbear.id.au
Thu Jun 11 00:51:45 MDT 2015


On Thu, 11 Jun 2015, Andrew Janke wrote:

> I have a perl script, one of its jobs is to concatenate a large number
> of (binary) files together.

> 2) Do it in bash
>
>     for i in infiles.txt; do cat $i >> result; done

Pretty sure that's wrong ;-)

> 3) Do it in perl

Good idea!


#!/usr/bin/perl -w

use strict;
use warnings;

use Fcntl qw (O_WRONLY O_CREAT O_TRUNC );
use FileHandle qw ();

sub catfiles {
   my ($out_filepath, $files) = @_;
   my $out = FileHandle->new($out_filepath, O_WRONLY|O_CREAT|O_TRUNC) or 
die "Crud: $!";
   foreach my $file (@$files) {
     my $stuff;
     my $in = FileHandle->new($file) or die "Crud ($file): $!";
     while (sysread($in,$stuff,16384)) {
       syswrite($out,$stuff,16384) or die "Failed to write: $!";
     }
   }
   $out->close() or die "Failed to close ($out_filepath): $!";
}

my $out = "/tmp/way-too-big.txt";
my @files = ('/etc/passwd','/etc/group');
&catfiles($out, \@files);


There's at least one bug in there :)


> 4) Something far more clever.

Not at this time of day :-)
>
> Suggestions welcome, my brain is slowing.

> a

Yours,
-- 
Peter Barker                          |   Programmer,Sysadmin,Geek.
pbarker at barker.dropbear.id.au	      |   You need a bigger hammer.
:: It's a hack! Expect underscores! - Nigel Williams


More information about the linux mailing list