map and grep again...

M

Marc Girod

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
 
S

sreservoir

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.
 
S

sln

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top