sara2005 has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
I define a hash table and an array upfront. Then, I want to read each element of the array, find if a 'key' exists in the hash table. If found, push the corresponding 'value' into a new array, if not, push the original element (read from the array) into the new array.
The program does what I expect it to do but I want to break the loop and contine with the next element in the array as soon as a match is found in
if ($_ eq $key){ ...
but, I am not too sure as to where to use the last or next command to break the loop as I didn't get the right results when I introduced last/next. Please help..
Here is the code:-
use Data::Dumper; use strict; # Define actual names (values) for the references (keys) in a hash tab +le my %mapped_vars = ( '1a' => 'One' '2a' => 'Tw +o', '3a' => 'Three', '4a' => 'Four' ); # List of array variables that has to be evaluated. It can also have n +ames that are NOT present in the hash table my @arr_vars = ( '3a','9d', '4a', '7b'); my (@act_vars, $i); my $found=0; # Checking... print Dumper(\%mapped_vars); print Dumper(\@arr_vars); foreach (@arr_vars){ while( (my $key, my $value) = each %mapped_vars){ print "$_-inside while()"; if ($_ eq $key){ push @act_vars, $value; $found =1; #last; } #last LBL; } unless ($found){ print "Inside unless()\n"; push @act_vars, $_; } $found = 0; print "\n"; } print Dumper(\@act_vars);
The Output is as follws:-
$VAR1 = { '3a' => 'Three', '2a' => 'Two', '4a' => 'Four', '1a' => 'One' }; $VAR1 = [ '3a', '9d', '4a', '7b' ]; --------------------------------------- 3a-inside while()3a-inside while()3a-inside while()3a-inside while() 9d-inside while()9d-inside while()9d-inside while()9d-inside while()In +side unless() 4a-inside while()4a-inside while()4a-inside while()4a-inside while() 7b-inside while()7b-inside while()7b-inside while()7b-inside while()In +side unless() ------------------------ $VAR1 = [ 'Three', '9d', 'Four', '7b' ];
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How to use 'last' / 'next' commands to exit loop?
by blazar (Canon) on May 30, 2006 at 17:29 UTC | |
by sara2005 (Scribe) on May 30, 2006 at 17:52 UTC | |
|
Re: How to use 'last' / 'next' commands to exit loop?
by borisz (Canon) on May 30, 2006 at 17:27 UTC | |
|
Re: How to use 'last' / 'next' commands to exit loop?
by Zaxo (Archbishop) on May 30, 2006 at 17:30 UTC |