Newbie question: load data to array

P

philbo30

I have a file with data like this:

123
456
789
010
987
654
321

I want to load these values into an array called "$data". How do I
make this happen?
 
C

charley

I have a file with data like this:

123
456
789
010
987
654
321

I want to load these values into an array called "$data". How do I
make this happen?

The manual explains this. See:

perlopentut
perlfunc (look for the function 'push')

Array names in perl are preceded with an '@' character, not '$'.

See: perlintro

Chris
 
M

Martijn Lievaart

I have a file with data like this:

123
456
789
010
987
654
321

I want to load these values into an array called "$data". How do I make
this happen?

open my $fh, "<", $filename or die "Cannot open $file: $!";
my @data;
while (<$fh>) {
push @data, $_;
}
close $fh;

or use File::Slurp.

HTH,
M4
 
B

Ben Morrow

Quoth Martijn Lievaart said:
open my $fh, "<", $filename or die "Cannot open $file: $!";
^^^^^^^^^ ^^^^^
One of these is not the same as the other... :)
my @data;
while (<$fh>) {
push @data, $_;
}

Huh? You're the second person who's suggested doing it like this... it's
really not necessary. Just use <> in list context:

my @data = said:
close $fh;

If you're not going to check the return value of close there's no need
(with a lexical FH) to call it. I would generally shorten the whole
thing to

my @data = do {
open my $FH, '<', $filename
or use File::Slurp.

....or that, yeah :).

Ben
 
T

Tad McClellan

Ben Morrow said:
Quoth Martijn Lievaart <[email protected]>:

If you're not going to check the return value of close there's no need
(with a lexical FH) to call it.


There's no need if the FH was opened for input.

If, however, it was opened for output, then an explicit close() is
a pretty good idea, even when you don't check its return value.

If you like to see others in pain, then check out my tale of woe:

http://groups.google.com/group/comp.lang.perl.misc/msg/73d4587743c64e2f
 
B

Ben Morrow

Quoth Tad McClellan said:
There's no need if the FH was opened for input.

If, however, it was opened for output, then an explicit close() is
a pretty good idea, even when you don't check its return value.

If you like to see others in pain, then check out my tale of woe:

http://groups.google.com/group/comp.lang.perl.misc/msg/73d4587743c64e2f

Yes, but that's about using global filehandles, which are only closed
when you re-open them. Lexical filehandles are explicitly closed by perl
at the point where they go out of scope, so don't cause that problem
(as, indeed, Anno pointed out in that thread... :) ).

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top