in reply to Adding to array

Read the new lines into a new list then push the new lines onto the end of the master list:

use strict; use warnings; my @list; foreach my $DIR qw(TEST_DIR WINS_DIR) { if (defined($ENV{"$DIR"})) { my $filename = $ENV{"$DIR"} . "/common/wins.ini"; if (-s $filename) { open (IN,$filename); my @newList = <IN>; close (IN); chomp @newList; push @list, @newList; } } }

Note too the use of strictures: use strict; use warnings;. All your code should use strictures!

Update: You may find that using next cleans up the code by reducing nesting thus making it easier to see the important program flow:

use strict; use warnings; my @list; foreach my $DIR qw(TEST_DIR WINS_DIR) { next unless defined($ENV{"$DIR"}); my $filename = $ENV{"$DIR"} . "/common/wins.ini"; next unless -s $filename; open (IN,$filename); my @newList = <IN>; close (IN); chomp @newList; push @list, @newList; }

Oh, and you should use the three parameter open too. ;)

open IN, '<', $filename;

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: Adding to array
by pglenski (Beadle) on Feb 28, 2007 at 20:55 UTC
    Thanks. The "next unless ..." is very good. BTW, I did use perl -w and use strict.

      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