Reputation: 41
So I want my perl file to read a file that contains two lines:
1 10 4
6 4
I want the the first line to to be @setA and the second line @setB. How do I do that without hard coding it?
Upvotes: 1
Views: 232
Reputation: 385789
my $setA = <$fh>; # "1 10 4"
my $setB = <$fh>; # "6 4"
Or
my @setA = split ' ', scalar(<$fh>); # ( 1, 10, 4 )
my @setB = split ' ', scalar(<$fh>); # ( 6, 4 )
Upvotes: 1
Reputation: 280
use strict;
use warnings;
use autodie qw(:all);
open my $file, '<', 'file.txt';
my @lines = <$file>;
my @setA = $lines[0];
my @setB = $lines[1];
print("@setA");
print("@setB");
close $file;
Upvotes: 0
Reputation: 15264
You would open the file to obtain a so-called filehandle (typically named $fh
), read the contents, and close the filehandle. Doing so involves calling open
, readline
, and close
.
Note readline also has a special syntax like <$fh>
. Reading lines usually follows the idiom:
while ( <$fh> ) {
# the line is in the $_ variable now
}
Then to tackle each line you'd use the split
function.
Another one that is occasionally useful is chomp
.
That should get you started.
Upvotes: 2