Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Opening an array of file names

by jwkrahn (Abbot)
on Apr 02, 2012 at 22:11 UTC ( [id://963125]=note: print w/replies, xml ) Need Help??


in reply to Opening an array of file names

sub getFiles { my @fileNames = [ "manimp1.txt", "manimp2.txt" ]; for my $i (0..$#fileNames) { open (FILE, "<", $fileNames[$i]) or die "Couldnt open file: $ +fileNames[$i]\n"; while (<FILE>) { $count++; my @line_array = split (/\t/, $_); chomp(@line_array); my $key = shift(@line_array); my $aref = [@line_array]; $newPrices{$key} = $aref; } delete ($newPrices{'Part Num.'}); } }

That would probably be better as:

sub getFiles { my @fileNames = ( 'manimp1.txt', 'manimp2.txt' ); for my $file ( @fileNames ) { open my $FILE, '<', $file or die "Couldnt open file: $file be +cause: $!"; while ( <$FILE> ) { chomp; my ( $key, @line_array ) = split /\t/; $newPrices{ $key } = \@line_array; } $count += $.; delete $newPrices{ 'Part Num.' }; } }

Replies are listed 'Best First'.
Re^2: Opening an array of file names
by tnyflmngs (Acolyte) on Apr 04, 2012 at 03:08 UTC

    Thanks for the input. The line:

    $newPrices{ $key } = \@line_array;

    is what I had originally, but my understanding is that is a reference to the array, and since the array changes when the next line is read, it made all the values in my hash the same, the last line of the last file. I understand that using  $newPrices{ $key } = [@line_array] creates a copy of the array. It is quite possible that I am mistaken since this is the first time I have really sat down with Perl.

      my ( $key, @line_array ) on the previous line creates a new variable each time through the loop so it is safe to use a reference to this variable.    If the variable was in a larger scope then what you describe would be a problem.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://963125]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-19 06:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found