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.

  • Comment on Re: Can map or splice replace my use of for loop + push + grep for my array transmogrification?
  • Select or Download Code

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

    Thanks much. I'm very appreciative. I'm just pointing out a wee typo, tho. You skipped a $.

    push @temp, map "$_.area$h", @shorts;

    ...unless you did that intentionally as some sort of test.

      unless you did that intentionally

      No, fixed.