Reputation: 1948
I have two arrays, I am evaluating the values of one array with other. What i have done is
@array_x= qw(1 5 3 4 6);
@array_y= qw(-3 4 2 1 3);
foreach $x (@array_x){
foreach $y (@array_y){
if ($x-$y > 0){
next;
}
print "$x\n";
}
}
Here, problem is , in array_x, its first index i.e 1-(-3)=4, it satisfies, but next 1-4=-3 is not satisfying the condition, hence it should break the loop and go for next element of array_x. Here only 5 and 6 satisfies the condition with all elements of array_y, so i should get only 5,6 in the output.
Upvotes: 3
Views: 241
Reputation: 7579
Revised answer:
#!/usr/bin/perl
use strict;
use warnings;
my @array_x= qw(1 5 3 4 6);
my @array_y= qw(-3 4 2 1 3);
LABEL: for my $x (@array_x) {
for my $y (@array_y) {
next LABEL unless $x > $y;
}
print "$x\n";
}
Upvotes: 0
Reputation: 20280
I think you might want to rethink your method. You want to find all values in @x
which are greater than all in @y
. You shouldn't loop over all @y
each time, you should find the max of it, then filter on the max.
use strict;
use warnings;
use List::Util 'max';
my @x= qw(1 5 3 4 6);
my @y= qw(-3 4 2 1 3);
my $ymax = max @y;
my @x_result = grep { $_ > $ymax } @x;
Or since I am crazy about the new state
keyword:
use strict;
use warnings;
use 5.10.0;
use List::Util 'max';
my @x= qw(1 5 3 4 6);
my @y= qw(-3 4 2 1 3);
my @x_result = grep { state $ymax = max @y; $_ > $ymax } @x;
Edit: on re-reading previous answers, this is the same concept as angel_007, though I think this implementation is more self-documenting/readable.
Upvotes: 0
Reputation: 9016
Here is your loops with labels so you can break to the outer level:
XVALUE:
foreach $x (@array_x){
YVALUE:
foreach $y (@array_y){
if ($x-$y > 0){
next XVALUE;
}
print "$x\n";
}
}
Upvotes: 4
Reputation: 103
If the intention is to just find the elements which are greater than the element in the subsequent list, the following would find it in 1 iteration of each array.
use strict;
my @array_x= qw(1 5 3 4 6);
my @array_y= qw(-3 4 2 1 3);
my $max_y = $array_y[0];
foreach my $y (@array_y) {
$max_y = $y if $y > $max_y;
}
foreach my $x (@array_x) {
print "\nX=$x" if $x > $max_y;
}
Output:
X=5
X=6
Upvotes: 3
Reputation: 2328
You can label each loop and exit the one you want. See perldoc last
E.g.:
LINE: while (<STDIN>) {
last LINE if /^$/; # exit when done with header
#...
}
Upvotes: 3
Reputation: 91385
Not really sure what is your need, but is this what you want?
#!/usr/bin/perl
use Modern::Perl;
my @array_x= qw(1 5 3 4 6);
my @array_y= qw(-3 4 2 1 3);
foreach my $x(@array_x){
my $OK=1;
foreach my $y(@array_y){
next if $x > $y;
$OK=0;
last;
}
say "x=$x" if $OK;
}
output:
x=5
x=6
Upvotes: 0