On 1/2/06, Gerard Robin <[EMAIL PROTECTED]> wrote:
> my @pack;
> my $j = 0;
>
> foreach my $i (0..$#array) {
>
>   if ($array[$i] eq '') {
>
>     $i++;
>
>   } else {
>
>     $pack[$j] = $array[$i];
>
>     $j++;
>
>   }
> }

You're right that this doesn't seem very Perl-ish. "Real Perl
programmers don't use subscripts." That's an exaggeration, but you
should generally prefer to avoid subscripting when Perl's other list
and array mechanisms are available. Maybe something like this:

  my @pack;
  my $empties = 0;
  foreach my $item (@array) {
      if ($item eq '') {    # empty string
          $empties++;
      } else {
          push @pack, $item;
      }
  }

The foreach loop avoids indexing into @array, and using push avoids
indexing into @pack.

You might be able to make another optimization in that code. Instead
of counting the empty strings as you go along, you could do some math
after building @pack:

  my $empties = @array - @pack;

That subtracts the number of elements of @pack from the number of
elements of @array (because subtraction provides scalar context).

Hope this helps!

--Tom Phoenix
Stonehenge Perl Training

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to