Reputation: 937
I'm trying to push information from file to array. I have file that looks like this:
1.2.3.4 => '"Something"'
5.6.7.8 => '"One more time"'
So the delimiter is "=>"
. So I try to push information from file to array like this:
my $filename = '/root/file';
open(my $filehandle, '<', $filename) or die "Could not open $filename\n";
my @resultarray;
while(my $line = <$filehandle>){
chomp $line;
my @linearray = split("=>", $line);
push(@resultarray, @linearray);
}
Then I try to remove whate spaces and quotes:
my @stripArray = grep(s/\s*$//g, @resultarray);
my @stripArray = grep(s/([^"]*)//, @stripArray);
print Dumper(@stripArray);
But all I get is:
$VAR1 = '';
$VAR2 = '"Something"';
$VAR3 = '';
$VAR4 = '"One more time"';
So the numbers are missing and the quotes are still there..... Trying to solve this riddle for about 3 hours, so thought it is time to ask for some help.
Upvotes: 0
Views: 253
Reputation: 6798
Input data are very easy to process with regular expression, extract information of interest and put it into array
use strict;
use warnings;
use feature 'say';
use Data::Dumper;
my @array;
while(<DATA>) {
my @data = /(\S+)\s+=>\s+"(.*?)"/;
push @array, \@data;
}
say Dumper(\@array);
__DATA__
1.2.3.4 => "Something"
5.6.7.8 => "One more time"
Or shorted version of same code
use strict;
use warnings;
use feature 'say';
use Data::Dumper;
my @array;
/(\S+)\s+=>\s+"(.*?)"/ && push @array, [$1,$2] while <DATA>;
say Dumper(\@array);
__DATA__
1.2.3.4 => "Something"
5.6.7.8 => "One more time"
Output
$VAR1 = [
[
'1.2.3.4',
'Something'
],
[
'5.6.7.8',
'One more time'
]
];
Upvotes: 0
Reputation: 241948
grep only returns the elements of the list that the expression returned true for. s///
returns false if there's nothing to substitute, so the numbers aren't returned from grep
.
Don't use grep
to change the elements of the list. That's what map
is for:
@stripArray = map s/\s+$//r, @resultarray;
You can also include the whitespace to the delimiter so you don't have to remove the spaces later:
my @linearray = split /\s*=>\s*/, $line;
Upvotes: 2