in reply to Can map or splice replace my use of for loop + push + grep for my array transmogrification?
First of all, don't modify the array over which for iterates.
If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body
Fixed:
my @temp; for my $h (@hosts) { if ($h =~ m/^\d{2}\z/) { for my $short (@shorts) { push @temp, "$short.area$h"; } } else { push @temp, $h; } } @hosts = @temp;
The inner for loop can be replaced with map simply:
my @temp; for my $h (@hosts) { if ($h =~ m/^\d{2}\z/) { push @temp, map "$_.area$h", @shorts; } else { push @temp, $h; } } @hosts = @temp;
You can also replace the exterior for loop with map too:
@hosts = map { if (/^\d{2}\z/) { my $h = $_; map "$_.area$h", @shorts } else { $_ } } @hosts
The above could be golfed, but I fear readability will suffer.
Filter isn't useful here since it only handles 1-to-1 transformations.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Can map or splice replace my use of for loop + push + grep for my array transmogrification?
by jffry (Hermit) on Nov 04, 2009 at 00:13 UTC | |
by ikegami (Patriarch) on Nov 04, 2009 at 00:19 UTC |