in reply to Ignore a range of numbers ina List
I first thought that Marshall's solution looked a bit complicated, but I ended up with something quite similar:
This may be slightly simpler, but only by a thin margin.#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my $aref = [6, 1, 7, 6, 2, 2, 7, 1, 6, 99, 99, 7, 88, 7, 6, 1, 2, 3]; my (@temp, @result); my $flag = 0; for my $num (@$aref) { $flag = 1 if $num == 6; if ($flag) { push @temp, $num; } else { push @result, $num; } if ($num == 7) { @temp = (); $flag = 0; } } push @result, @temp; print Dumper \@result;
Using references to the @result and @temp arrays rather that a $flag can make the for loop significantly shorter:
but this may seem less simple, at least for a beginner.#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my $aref = [1, 7, 6, 2, 2, 7, 1, 2, 6, 99, 99, 7, 88, 7, 6, 1, 2, 3]; my (@temp, @result); my $target_ref = \@result; for my $num (@$aref) { $target_ref = \@temp if $num == 6; push @$target_ref, $num; $target_ref = \@result, @temp = () if $num == 7; } push @result, @temp; print Dumper \@result;
Output:
$ perl range4.pl $VAR1 = [ 1, 7, 1, 2, 88, 7, 6, 1, 2, 3 ];
|
---|