A Look at Contexts in Perl

From AndrewMoore

Jump to: navigation, search

An interesting topic came up recently on the perl5-porters list. Schwern wrote that perhaps a warning should be emitted when grep is used in void context, when the return value was ignored.

grep do_something() @list;

That does look odd at first glance. The return values of do_something() are examined by grep, but ignored. Why did we grep for anything?

In #p5p, Shwern went on to point out that that's probably an obfuscated case of map in a void context:

map do_something() @list;

which itself is an obfuscated case of for:

do_something() for @list;

But, it turns out that each of these cases is different in the context that do_something() is in.

EXPR for @list;   # EXPR in void context
grep EXPR, @list; # EXPR in scalar context
map EXPR, @list;  # EXPR in list context

That's exactly the kind of thing I never think of. Well, they still look a but obfuscated to me, so perhaps I'll use these constructs to force the context in the future:

EXPR for @list;        # EXPR in void context
scalar EXPR for @list; # EXPR in scalar context
[ EXPR ] for @list;    # EXPR in list context

Thanks to the guys in #p5p for pointing this out and helping me understand it.

Share This Page
  • Stumble It!