in reply to Re: Adding to array
in thread Adding to array

Thanks. The "next unless ..." is very good. BTW, I did use perl -w and use strict.

Replies are listed 'Best First'.
Re^3: Adding to array
by GrandFather (Saint) on Feb 28, 2007 at 21:05 UTC

    Always declare variables in the smallest scope you can. There is a nasty trap implied by your code. Consider:

    use strict; use warnings; my $var = 'wibble'; foreach $var qw(foo bar) { print "$var\n"; } print $var;

    Prints:

    foo bar wibble

    Did you expect 'wibble' or 'bar' for that last value?

    The $var you declared outside the loop is not the $var used inside the loop. The loop variable is aliased to each value the loop iterates over. Using the form for my $var makes it clear to everyone that the scope of $var is just the loop and avoids the unfortunate assumption that the last value "assigned" to $var is available after the loop. Not a problem for your sample code, but a nasty trap waiting to bite you one day.


    DWIM is Perl's answer to Gödel