There's More Than One Way To Do It, of course, and the following will provide some examples, in order from least idiomatic to most idiomatic. You can see it run if you plop it into your editor.
use strict; use Data::Dumper; #fill an array with content of __DATA__ my @data; while (<DATA>) { chomp; push @data, $_ } #ugliest way - use regex & matches - shudder! print "Ugliest Way:\n"; foreach my $line (@data) { $line =~ /^(\d+)\+(\d+)\s(\w+)\s(\w+)/; my $first = $1; my $second = $2; my $third = $3; my $fourth = $4; print "$first:$second:$third:$fourth\n"; } #slightly less ugly way - exploit list context print "\nSlightly Less Ugly Way:\n"; foreach my $line (@data) { my ($first, $second, $third, $fourth) = $line =~ /^(\d+)\+(\d+)\s(\w+)\s(\w+)/; print "$first:$second:$third:$fourth\n"; } #decent way - use split instead of regex print "\nDecent way:\n"; foreach my $line (@data) { my ($first, $second, $third, $fourth) = split (/\+| /, $line); print "$first:$second:$third:$fourth\n"; } #okay way - load values into a hash for later use #assuming the first element is the one on which lookups will #occur most frequently. Hashes are great for finding keys quickly. print "\nOkay Way:\n"; my %hash1; foreach my $line (@data) { my ($first, $second, $third, $fourth) = split (/\+| /, $line); $hash1{$first}{SECOND} = $second; $hash1{$first}{THIRD} = $third; $hash1{$first}{FOURTH} = $fourth; } print Dumper(%hash1); #equally okay way - load values into two-dim array print "\nEqually Okay Way:\n"; my @array; foreach my $line (@data) { #square brackets give you a ref to the array produced #by the split push @array, [split (/\+| /, $line)]; } print Dumper(@array); 1; __DATA__ 8294750274534+4821 kudu AUG 3249230958867+9462 firkt BOD 482048348344+8467 kwirk NAR 3242359960+5487 mana GOW 3948585747757+48 ala SAN 348838482348+6487 kudu AEG 4234985745534+82 pira AEG
There are even more elegant ways of accomplishing this, and probably a CPAN module or two, but you have to walk before you can run. ;)
In reply to Re: select line from file
by Art_XIV
in thread select line from file
by help
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |