Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Ovid (2709)

Ovid
  (email not shown publicly)
http://publius-ovidius.livejournal.com/
AOL IM: ovidperl (Add Buddy, Send Message)

Stuff with the Perl Foundation. A couple of patches in the Perl core. A few CPAN modules. That about sums it up.

Journal of Ovid (2709)

Sunday April 09, 2006
02:40 PM

Marching two by two

[ #29268 ]

Well that was fun to write.

foreach my $i ( grep { !( $_ % 2 ) } 0 .. $#_ ) {
    ...
}

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • foreach my $i ( map { $_ * 2 } 0 .. $#_ / 2 ) {
        ...
    }

    ?

    • foreach my $i ( grep { ~$_ & 1 } 0 .. $#_ ) {
          ...
      }
      ?
      --
      perl -e 'print "Just another Perl ${\(trickster and hacker)},";'
      The Sidhekin proves that Sidhe did it!
      • Same thing as Ovid’s, only painted green. Both his and yours make two to throw one away, whereas the approach I took does not.

        • for ( my $i = 0 ; $i <= $#_ ; $i += 2 ) {
              ...
          }
          ?
          --
          perl -e 'print "Just another Perl ${\(trickster and hacker)},";'
          The Sidhekin proves that Sidhe did it!
          • This one scores highest on readability. I assert that the other ones are too hard to understand and, thus, more likely to be buggy (i.e. off-by-one errors).

            I think the best version is simply:

                    for ( my $i = 0; $i @_; $i += 2 ) { ...
                    }

            It clearly selects even numbers and ends before just before the end of the array. The "@_" is more readable than "$#_", I say.
            • foreach my $i ( 0 .. $#_ / 2 ) {
                  my $j = $i * 2;
                  ...
              }

              ?

              The most readable is actually if you can afford to destroy the array, which in Ovid’s case is probably true (because it is usually true for @_):

              while( @_ ) {
                  ...
                  splice @_, 0, 2;
              }