in reply to modifying a file with regex!

This is how I'd do it...

#!/usr/bin/perl use autodie; # Automatic errors on file problems. use strict; # This is the name of the file we want to modify. my $filename = 'modify-file.txt'; # We're going to create a temporary file. This avoids us having # to build up a potentially large string in memory. my $tempname = $filename . '.tmp'; do { # Open both files. Doing this using lexical file handles # within a "do" block means that when the end of the block # is reached, the files will be closed. open my $input_h, '<', $filename; # input handle open my $output_h, '>', $tempname; # output handle # Loop through each line of input. while (<$input_h>) { # Modify the line s/^>Sample_(\d+)_x(\d+)/>ID$1 $2/i; # Write it out. print $output_h $_; } }; # Delete the original file. unlink $filename while -f $filename; # Rename the temporary file to the original filename. rename $tempname => $filename;
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^2: modifying a file with regex!
by Marshall (Canon) on Mar 16, 2012 at 22:56 UTC
    This extraneous "do" is completely unnecessary. It actually "harms" by introducing an unnecessary level of indentation - which is a hindrance to readability.

      It eliminates two calls to close and allows some lexical variables ($input_h and $output_h) to live in a smaller scope.

      Indent it however you like; this ain't Python.

      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
        Calls to close() are not necessary in any event (for this particular code). Code runs the same with or without the "do". The only argument in favor of this "do" is scope of $input_h, etc. The price of the extra indentation level is too high and the gain too low - because of the very limited "life" of these variables.

        I guess like all things, mileage may vary. In Perl, you can eliminate the "do" and just put {}, however I don't think either of these wise in this situation. Obviously you disagree.