Common utilities meme

Posted by Chris on June 2nd, 2008 filed in Uncategorized

There’s a meme going around where people show their “utilities”.  Little snippets of code that follows them from place to place and from program to program.  So here’s one of mine that I’ve been using in one form or another for a long, long time.  All it does is take a file and optional comment string – open the file, read the lines into an array, and optionally remove lines with the comment string then return the array.  It’s super easy to do without a helper function, but I do it so often that the one line it takes (two if you count the include or require) is worth it.

This is *actual* code here, I haven’t cleaned it up at all.

#readlines(‘filename’); will return an array of the contents of a file. No newlines present, but some minimal
error checking.
sub readlines
{
my $filename=shift;
my $skip =shift;
if(! -e $filename) {die(“File $filename doesn’t exist”);}
open(F,$filename)
or die(“Couldn’t open file $filename for reading: $!”);
my @lines=<F>;
close(F) or die (“Couldn’t close file $filename: $!”);
chomp(@lines);
if($skip)
{
my @retary=();
foreach my $line(@lines)
{
$line=~s/^(.*?)$skip.*/$1/;
if(!$line){next;}
push(@retary,$line);
}
@[email protected];
}
return @lines;
}

Leave a Comment