[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] passwd file fwacking (fwd)



---------- Forwarded message ----------
From: Jeff Pinyan <jeffp@crusoe.net>
To: Bennett Todd <bet@rahul.net>

>I only ever used map BLOCK LIST, never paid any attention to the
>alternative. Makes sense that EXPR, LIST would run faster.

I wince slightly when I see constructs like

  @silly_way_to_unpack = map { ord } split //, $name;

(Yes, poor example, since unpack("C*", $name) is much better.)

I've done benchmarks that show that

  map ord, split //, $name;

is faster.  And you can make it more readable with the => operator:

  map ord() => split //, $name;

The parens are needed, since => forces bareword context on its LHS.

I even use map EXPR, LIST for complex expressions; this reinforces the
beauty of the unary plus operator:

  map ($_->[0], $_), @list;  # this is wrong
  # perl sees that as
  (map $_->[0], $_), @list;

  map { $_->[0], $_ } @list;  # sure, you could use a BLOCK...

  map +($_->[0], $_), @list;  # or use unary + to change the ()'s
                              # from an argument list, to grouping

For an example of complex EXPRs, here's my grep-sift from yesterday's
discussion:

  sub sift {
    my @in = @{+shift};
    my @s;

    for my $r (@_) {
      $r = qr/$r/ if ref $r ne "Regexp";
      my ($i,$j) = (0,0);
      push @s, grep +(
        $j++,
        $_ =~ $r and ( splice(@in,$j-1-$i,1), ++$i )
      ), @in;
    }

    return (@s,@in);
  }

Using grep EXPR, LIST proved much faster in critical benchmarking tests
than

  push @s, grep {
    $j++,
    $_ =~ $r and ( splice(@in,$j-1-$i,1), ++$i )
  } @in;

By the way, this is a recent chunk of beautiful code I came up with -- it
successfully modifies @in AS grep() iterates over it.

Glad I could be of service, and I definitely enjoy discussing small things
like this.

-- 
MIDN 4/C PINYAN, NROTCURPI, US Naval Reserve             japhy@pobox.com
http://www.pobox.com/~japhy/                  http://pinyaj.stu.rpi.edu/
PerlMonth - An Online Perl Magazine            http://www.perlmonth.com/
The Perl Archive - Articles, Forums, etc.    http://www.perlarchive.com/



==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe