For the first question: you are dealing with a multiline match, in the sense that after name is found any num belong to it. This is achieved better with something like $current_name initialized out of the loop. you were right with the `push @{hash1{name1}},$x1,$y1,$x2,$y2` tecnique but you missed a dollar sigyl before name1: in your actual code with the statement $hash1{$name1}=[$x1,$y1,$x2,$y2]; you are reinizialing the value to a new array each time.
Notice that I used push @{$hash1{$current_name}}, $_ for $line =~ /\d+/g pushing all numbers into the array: perhaps you want more robust control appending a check like: if $line =~/^num\s+\d/
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $current_name; my %hash1; while (my $line = <DATA>){ chomp $line; if($line =~ /^name\s+(\S+)/) {$current_name = $1;} push @{$hash1{$current_name}}, $_ for $line =~ /\d+/g } print Dumper \%hash1; __DATA__ name foo num 111 222 333 444 name jack num 999 111 222 333 num 333 444 555 777
See the above running at webperl demo by haukex (oh oh oh!;)
L*
UPDATE
for the second question you can profit of the exists function: foreach key of the first hash, if exist the same in the second one, you print also the second list. If you want values in group of four it's a bit trickier but feasible
UPDATE October 22 in reponse to Re^2: how to push multiples row of values into hash and do comparison
$_ is the default input variable in perl: see perlvar
In my code I use it only in the push @{$hash1{$current_name}}, $_ for $line =~ /\d+/g statement. Let's reduce the example a bit. The g modifier in the regex in list context returns the list of all matches: see it in perlrequick so $line =~ /\d+/g returns a list.
The first part push @{$hash1{$current_name}}, $_ push into the array the default variable of the foreach loop aka $_ so translated to english sounds like: push in this array every match obtained matching one or more number in this line.
In reply to Re: how to push multiples row of values into hash and do comparison
by Discipulus
in thread how to push multiples row of values into hash and do comparison
by darkmoon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |