How can I iterate over an array from the first occurrence of an element with a specific value using perl?

I have an array like ("valueA", "valueB", "valueC", "valueD") etc. I want to iterate over the values ​​of the array, starting with (for example) the first instance of "valueC", Everything in the array until the first instance of the value "valueC" should be ignored; therefore, in this case, only the cycle "valueC" and "valueD" is processed by the cycle.

I can just set a condition inside my loop, but is there an easier way to express an idea with perl?

+4
source share
6 answers
my $seen; for ( grep $seen ||= ($_ eq "valueC"), @array ) { ... } 
+6
source
 my $seen; for ( @array ) { $seen++ if /valueC/; next unless $seen; ... } 

But this $seen bit uncomfortable. The flip-flop statement looks a tidier IMO:

 for ( @array ) { next unless /^valueC$/ .. /\0/; # or /^valueC$/ .. '' !~ /^$; # or $_ eq 'valueC' .. /\0/; ... } 

Or simply (based on ikega):

 for ( grep { /^valueC$/ .. /(*FAIL)/ } @array ) { ... } 
+6
source

I think you also need to check if "valueC" exists inside the array.
Hope this helps.

 use strict; use warnings; use List::Util qw(first); my @array = qw(valueA valueB valueC valueD); my $starting_element = 'valueC'; # make sure that the starting element exist inside the array # first search for the first occurrence of the $stating_element # dies if not found my $starting_index = first { $array[$_] eq $starting_element } 0 .. $#array or die "element \"$starting_element\" does not exist inside the array"; # your loop for my $index ($starting_index .. $#array) { print $array[$index]."\n"; } 
+6
source

TIMTOWTDI, but I think that:

 foreach my $item (@list) { next if !$seen && ($item ne 'valueC'); $seen++; ... } 

It is quite readable, correct and concise. Everything / valueC / solution will handle anything after "DooDadvalueCFuBAr", not what the OP sets. And you don’t need a flipflop / range operator, and checking for the presence is actually really strange, in addition, requiring a possibly incompatible package to perform a rather trivial task. The grep solution really makes me spin my head, besides creating and throwing up the tempo of the array as a side effect.

If you want some fantasy and avoid "ifs":

 foreach my $item (@list) { $seen || ($item eq 'valueC') || next; $seen++; ... } 

Just don't write home about it. :-)

+2
source
 use List::MoreUtils qw( first_index ); foreach my $item ( @array[ ( first_index { $_ eq 'ValueC' } @array ) .. $#array ] ){ # process $item } 
+2
source
 my $start = 0; ++$start while $start < @array && $array[$start] ne 'valueC'; 

followed by either

 for (@array[$start..$#array]) { say; } 

or

 for my $i ($start..$#array) { say $array[$i]; } 
+2
source

Source: https://habr.com/ru/post/1389088/


All Articles