From: Marc Girod on 16 Jul 2010 10:50 Hello, I know this has been explained earlier... but why are map and grep behaving differently here? #!/usr/bin/perl -w use strict; use feature qw(say); my @glb = qw(lbtype:FFF); say $_ for map { s/^lbtype:(.*)(\@.*)?$/$1/ } @glb; @glb = qw(lbtype:FFF); say $_ for grep { s/^lbtype:(.*)(\@.*)?$/$1/ } @glb; Running this gives: $ /tmp/foo 1 FFF Thanks, Marc
From: sreservoir on 16 Jul 2010 11:05 On 7/16/2010 10:50 AM, Marc Girod wrote: > Hello, > > I know this has been explained earlier... but why are map and grep > behaving differently here? > > #!/usr/bin/perl -w > > use strict; > use feature qw(say); > > my @glb = qw(lbtype:FFF); > say $_ for map { s/^lbtype:(.*)(\@.*)?$/$1/ } @glb; map collect return values. > @glb = qw(lbtype:FFF); > say $_ for grep { s/^lbtype:(.*)(\@.*)?$/$1/ } @glb; grep collects when return value is true. > Running this gives: > > $ /tmp/foo > 1 > FFF for (@glb) { s///; say } of course. s/// return 1 or !1, depending whether something was matched or replaced. please don't use map and grep purely for side-effects unless you know what you're doing. and you don't have to specify the implicit argument. -- "Six by nine. Forty two." "That's it. That's all there is." "I always thought something was fundamentally wrong with the universe."
From: Marc Girod on 16 Jul 2010 11:16 On Jul 16, 4:05 pm, sreservoir <sreserv...(a)gmail.com> wrote: > map collect return values. > grep collects when return value is true. Thanks. Marc
From: sln on 16 Jul 2010 13:32 On Fri, 16 Jul 2010 07:50:10 -0700 (PDT), Marc Girod <marc.girod(a)gmail.com> wrote: >Hello, > >I know this has been explained earlier... but why are map and grep >behaving differently here? > >#!/usr/bin/perl -w > >use strict; >use feature qw(say); > >my @glb = qw(lbtype:FFF); >say $_ for map { s/^lbtype:(.*)(\@.*)?$/$1/ } @glb; >@glb = qw(lbtype:FFF); >say $_ for grep { s/^lbtype:(.*)(\@.*)?$/$1/ } @glb; > >Running this gives: > >$ /tmp/foo >1 >FFF > >Thanks, >Marc map {} .. is going to give you the result of the operation. The line with map is creating a list with the result of the regular expression. Grep is is creating a list of sucessfull matches. You confuse the issue when you when you stick map or grep inside the for expression then put the default $_ inside its body. Obviously each is say(ing) the itterative list values AFTER the list is created. So, say $_ for map { s/^lbtype:(.*)(\@.*)?$/$1/ } @glb; ^^ is NOT { $_ =~ s/^lbtype:(.*)(\@.*)?$/$1/ } ^^ Nothing wrong with clarity. print "----\n"; @glb = qw(lbtype:FFF); @list = map { s/^lbtype:(.*)(\@.*)?$/$1/ } @glb; for (@list) { say $_; } @glb = qw(lbtype:FFF); @list = map { s/^lbtype:(.*)(\@.*)?$/$1/; $_ } @glb; for (@list) { say $_; } print "----\n"; @glb = qw(lbtype:FFF); @list = grep { s/^lbtype:(.*)(\@.*)?$/$1/ } @glb; for (@list) { say $_; } -sln
|
Pages: 1 Prev: Is Mason dead? Was: MasonCompRoot and globs Next: debugging Carp |