in reply to A perverse use of grep

You were right in the code smell, but wrong in your fix. It's poor style because someone's trying to be cool and do everything on one line. Instead, the code should really be something like:
my @lines; { local $_; while ( <$in> ) { # Remove leading and trailing whitespace s/^\s+//; s/\s+$//; # Remove comments from the first # to the end of the line s/#.*//; push @lines, $_ if length $_; } }
Are you paying for your whitespace or something??

Update: Fixed bug as per brian_d_foy's comment.

Update: Changed per demerphq's comment.

Update: Added bare-block to localize $_ per itub's comment. I don't think this is completely necessary, but it's good to be anal.


  • In general, if you think something isn't in Perl, try it out, because it usually is. :-)
  • "What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?"

Replies are listed 'Best First'.
Re^2: A perverse use of grep
by brian_d_foy (Abbot) on Jun 15, 2005 at 03:05 UTC

    Your code reproduces the bug of ignoring the line that is the bare '0'. You don't want to test the value of the line, but its length.

    --
    brian d foy <brian@stonehenge.com>
Re^2: A perverse use of grep
by eyepopslikeamosquito (Archbishop) on Jun 15, 2005 at 03:16 UTC

    Well, it is not "my" code; I inherited it and have to maintain it. Despite my dubious past as a golfer, I never play golf on production code. ;-) I like your approach, BTW.

Re^2: A perverse use of grep
by demerphq (Chancellor) on Jun 15, 2005 at 09:44 UTC

    IMO the expanded style is bad form:

    while ( defined( $_ = <$in> ) )

    should be written

    while (<$in>) {
    ---
    $world=~s/war/peace/g

      I would also recommend localizing $_, because while doesn't do it automatically:
      sub whatever { local $_; while(<$in>) { # do stuff } }

      Even if the loop is not in a sub, localizing $_ can prevent nasty bugs if you decided to wrap the loop in a sub later.

      You're right ... I originally had while (defined( my $line = <$in> )) and never got rid of the expanded form when I went back to $_. Updated.

      • In general, if you think something isn't in Perl, try it out, because it usually is. :-)
      • "What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?"