Sunday, September 20, 2009

giving some love to do

The do {} construct does not get much love in most of the code I see. Besides do {} while loops, it is very useful for combining steps and limiting the scope of variables:
my $contents = do {
local $/;
open my $fh, "<", $filename
or die "could not open $filename: $!";
<$fh>;
};
The snippet above keeps the change to $/ and the $fh variable local to the section that needs it.

2 comments:

  1. Yeah, I really like that.

    Something I often do (well, over several lines) is

    my @file = do { use autodie; opendir my $dh, $directory; readdir $dh };

    which limits the scope of the directory handle so I don’t need to close it, and segregates the “slurp directory contents” piece of the code into one block.

    ReplyDelete
  2. I often use this for slurping:

    my $contents = do { local (@ARGV, $/) = "filename"; <> };

    Needs more error checking of course, but for one-off scripts its great,

    ReplyDelete

Some limited HTML markup is allowed by blogger: strong, b, i, and a. You may also use em, but I have repurposed it through the magic of CSS to be behave very much like <tt><code></code></tt>.