'Perl - reading file into multidimension array
I am hoping someone can assist me, I am fairly new to Perl, I have looked and found some sample scripts but cannot get this to work.
I have input file that is generated by a SQL query:
0050560A49871EEBAE9D90FC8C9E1808 d:\ 060606 812
aaaaemsmf61wbjmqmiaaezroku2u3 d:\ 060606 817
aaaaemsmf61wbjmqmiaaezroku2u3 d:\ 060606 817
aaaacodrditwbjvwwqaaaaboku2u3 d:\ 060606 820
aaaacodrditwbjvwwqaaaaboku2u3 d:\ 060606 820
(5 rows affected)
Using the following code I am trying to read the contents into a multidimensional array :
my $data;
my $fields = {};
read_folder();
for ($i = 0; $i < $input_file_number; $i++){
my $file = "./extracted/$sql_scripts[$i]";
printf "file = $sql_scripts[$i]\n";
open($data, '<:encoding(UTF-8)',$file) or die "Could not open '$file' $!\n";
while (<$data>)
{
push @fields, [split/s+/];
}
print Dumper( @fields ), "\n\n";
}
However when I user the print Dumper command it shows that each line from the file has been put into the array but has not split the lines when a space occurs, am i using the push @fields, [split/s+/]; command wrong ? In additon I would like to remove the whitespace betweeen each value on the line, when added to the array.
Any help will be much appricated
Solution 1:[1]
The regex pattern s+ matches one or more s, so the following is wrong:
push @fields, [ split /s+/ ]; # Short for: `split /s+/, $_, -1`
You want \s+: one or more whitespace character.
push @fields, [ split /\s+/ ]; # Short for: `split /\s+/, $_, -1`
Alternatively, you could pass a single space to split. This is a treated specially, and it's almost identical to using \s+. The only difference is that passing a single space causes the split to ignores leading whitespace in the input.
push @fields, [ split ]; # Short for: `split " ", $_, -1`
Solution 2:[2]
Managed to figure it out, by changing the line
push @fields, [split/s+/];
to
push @fields, [split " "];
I accomplish both the data being split by the values, and also the whitespace is removed
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ikegami |
| Solution 2 | Sunny |
