May 2006
Beginner
298 pages
6h 51m
English
File off the rough edges of your code.
Sit down and look at the code you actually write every day. Is there something tedious that you do all the time, something that is a tiny (but constant) irritation? Maybe it's as simple as adding that final "\\n" to the end of just about every print command:
print "Showing first ", @results / 2, " of ", scalar @results, "\\n";
for (@results[ 0 .. @results / 2 - 1 ])
{
if (m/($IDENT): \\s* (.*?) \\s* $/x)
{
print "$1 -> ", normalize($2), "\\n";
}
else
{
print "Strange result: ", substr( $2, 0, 10 ), "\\n";
}
}If you find that you have to tack a newline onto the end of most (or even just many) of your print statements, factor out that tiny annoyance:
sub say { print @_, "\\n" }
# and ever after...
say "Showing first ", @results / 2, " of ", scalar @results;
for (@results[ 0 .. @results / 2 - 1 ])
{
if (m/($IDENT): \\s* (.*?) \\s* $/x)
{
say "$1 -> ", normalize($2);
}
else
{
say "Strange result: ", substr( $2, 0, 10 );
}
}Likewise, if you're forever opening a file and reading in the contents:
open my $fh, '<', $filename or die "Couldn't open 'filename'";
my $contents = do { local $/; <$fh> };you could automate that:
sub slurp
{
my ($file) = @_;
open my $fh, '<', $file or croak "Couldn't open '$file'";
local $/;
return <$fh>;
}
# and thereafter:
my $contents = slurp $filename;The key here is to find the repetitive, low-level, mechanical things you do and hoist them out of your code ...