Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Easy Reference for Contexts

by cat_baby (Novice)
on Apr 14, 2011 at 06:53 UTC ( [id://899364]=perlquestion: print w/replies, xml ) Need Help??

cat_baby has asked for the wisdom of the Perl Monks concerning the following question:

Hello, wise Perl friends.

There ought to be a repository of common expressions and how they behave in each context / what their default context is. I know there are tons of vanilla examples found in tutorials everywhere (such as assigning an array to a scalar) but some slightly more sophisticated operations still trip me up.

For example:

m/.../ returns true or false in scalar context m/.../g give you a list of matches in list context m/(...)/ can populate an array with whatever gets captured... (??)
while( ) i.e. inside parenthesis is evaluated in scalar context? foreach( ) i.e. inside parenthesis is evaluated in list context?
<STDIN> returns the next line of input in list context

In fact, I could be wrong on a lot of these but that's not my point. Is there a handy reference-like guide available anywhere that tells you how these expressions behave?

Replies are listed 'Best First'.
Re: Easy Reference for Contexts
by davido (Cardinal) on Apr 14, 2011 at 07:23 UTC

    Your questions on regular expressions, and what they do in various contexts, with and without capturing parenthesis would probably be answered in perlre, perlrequick, and perlretut. There is additional reading proscribed at the bottom of each of those docs.

    perlsyn discusses while(){}, but think of it this way: while evaluates a condition. In other words, while some condition exists, the loop proceeds. It's more akin to an "if()" statement except that the test repeats again and again until it fails. The test is a Boolean test; true or false. It doesn't make sense to discuss list context in terms of a Boolean evaluation.

    foreach(), on the other hand, is an iterating loop construct. The Perl-style foreach iterates over a list of elements until it finishes with the last one. For each element in the list, there's one iteration, or one execution of the code within the blocks. In such a case it should be fairly obvious that the context is list context. On the other hand, the C style foreach loop is a bit of a special case. It provides a mechanism for the creation of a counter variable, does a conditional test (which is Boolean), and then provides a mechanism for incrementing the counter. But in this special case, it doesn't make sense to be talking about list context. In fact, perlop (in the section talking about IO operators) alludes to the fact that a for(;;) loop is sort of a disguise for a while() loop. So you could almost have a mind-entry of "Foreach (;;) (c-style loop): See also while()."

    <STDIN> is pretty well documented in perlop. In scalar context it returns one record (or line). In list context, it returns all records (or lines) as separate list elements. In Boolean context it throws a warning under -w.

    I actually think that after reading perlintro, perlsyn, perlop, and perlre you will have just about covered 90% of your context questions. And if you're really interested in Perl you were going to read those anyway. :)


    Dave

Re: Easy Reference for Contexts
by wind (Priest) on Apr 14, 2011 at 07:19 UTC
Re: Easy Reference for Contexts
by JavaFan (Canon) on Apr 14, 2011 at 10:52 UTC
    There ought to be a repository of common expressions and how they behave in each context
    The perl documentation does that, doesn't it? perlop and perlfunc would be the places to look first.
    what their default context is
    There's no default context. An expression is always in a context. And it's always the caller that determines the context - there's no operator/function that says "you know what, I let my operands run in their default context". (And how could it?)
      > > what their default context is
      > There's no default context.

      with a little more tolerance in interpretation of "context":

      IIRC some operands and builtins only work in special contexts, some even throw (threw?) warnings if not used properly.

      > > There ought to be a repository of common expressions and how they behave in each context
      > The perl documentation does that, doesn't it?

      Well I once meditated over this, unfortunately POD doesn't have a standard notation for a brief definition for the interface of a term.

      If it had, they could not only automatically be compiled into cheat sheets, but also into tool tips for IDEs or grammatical rules for syntax checkers.

      There are various alternative sources for such abstracts, which get hopelessly fast outdated

      For instance emacs's cperl-mode has tool-tips hardcoded which are far from being up-to-date.

      Another advantage of such an hypothetical POD-extension could be the definition of use cases for snippet-expansion within an IDE, like for yasnippet in emacs or more detailed error-texts for diagnostics.

      Of course some (all?) of this could be achieved with a special =FOR :format-paragraph, but there is no standard notation yet. (maybe Perl6 signatures could be a good start)

      Cheers Rolf

        Padre/../PPI? B::Deparse::ContextAnnotate? Perl::Tidy::ContextAnnotate?

        Hmm ... delicious ideas .... ...

        … … … .__,,,_._,--~~~~~---,,_
        … … ,,-"… .,~". . . . . . . . . . . . ."~-,
        … …,/-~-,-". . . . . . . . . . . . . . . . . . ."~,,___
        … ,-".|..,-". . . . . . . . . . . . . . . . . . . . . . . . .~'~--,,_
        ... /… \". . . . . . . . . . . . . . . . . . . . . . . . . . . . . __,'\
        … \..,/."-. . . . . . . . . . . . . . . . . . . . . ."~,,. .,,-~'--': : |
        … ."-'. . . . . . . . . . . . . . . . . . . . . . ._,,-~'\": : :,~"``"~,
        … ..|.". . . . . . . . . . . . . . . . . . . ,-,": : : : : :|:,,-". . . . . |
        … ..|. . . . . . . . . . . . . . \. . . . ,-"~': : : : : : /. . . . . . . ./~---,,_
        … ...\. . . . . . . . . . . . . . \. . ,-": : : : : : : : /. . . . . ,-~"'………."~-,
        … … '\. . . . . . . . . . . . . .",": : : : : : : _,-". . . ,-~"…………………"\
        … … .."-,. . . ,_. . . . . . . . ―"~~----~". . . ,-~"…………….._,,--~,,../
        … … … ."~,. . \,"~,_. . . . . . . . . . . . . .,-"……………,,~": :,,,-,'~',/
        … … … … ,",-,. "-,. ."~. . . . . . . . . . ,-"………….,~":,,,,,--":,-".,-"
        … … … … ."-,.."~,". _,. . . . . . . . . ,/…………,~": ,-",-"_,"".,-"
        … … … … … \… ,-". __, . . . . . . ,/………...,-": ,"';/―,"…,~"
        … … … … … … .\. .".\. . .,. . . . ./……….,-"_,,-";;;\,/..,-"
        … … … … … … ..."~~-,--". . . ./………,-": /;;;;;;;;;/../
        … … … … … … … … .|. . . . . |……..,/~~';;;;;;;;;;;|...'\,
        … … … … … … … … .|. . . . . |……./;,-~~--,-~~-,"-….|
        … … … … … … … … .|. . . . . .\…...|-"::::::::":::::::\... |
        … … … … … … … .SL|. . . . . . \,….."--,--"-,:::::::::/..,/
        … … … … … … … … .|. . . . . . . "~,……――"~--~"..,/
        … … … … … … … … .|. . . . . . . . . ."~~---,,,,,,--~"\
        … … … … … … … … ..――"'~~~~---------,,,,,,,,,_____\
        ---
Re: Easy Reference for Contexts
by ikegami (Patriarch) on Apr 14, 2011 at 15:54 UTC

    Honestly, the answers are usually obvious.

    while( ) i.e. inside parenthesis is evaluated in scalar context?

    It needs a single true/false value. What context do you think it imposes?

    foreach( ) i.e. inside parenthesis is evaluated in list context?

    It iterates over a list. What context do you think it imposes?

    The are two areas of confusions.

    • Where prototypes are involved.

      sub plain { print $_[0]; } sub proto($) { print $_[0]; } my @a = 4; plain(@a); # 4 proto(@a); # 1

      Most builtins have prototypes, so passing an argument list from an array rarely works with them.

    • There are two different assignment operators. One imposes a scalar context on its LHS and RHS operand, while the other imposes list context on its LHS and RHS operands. It should be still be intuitive, but you might want to check out Mini-Tutorial: Scalar vs List Assignment Operator.

Re: Easy Reference for Contexts
by Anonymous Monk on Apr 14, 2011 at 10:01 UTC
Re: Easy Reference for Contexts
by LanX (Saint) on Apr 14, 2011 at 13:42 UTC
    m/.../ returns true or false in scalar context m/.../g give you a list of matches in list context m/(...)/ can populate an array with whatever gets captured... (??) while( ) i.e. inside parenthesis is evaluated in scalar context? foreach( ) i.e. inside parenthesis is evaluated in list context? <STDIN> returns the next line of input in list context

    Well ... most of this can be tested interactively.

    The inside context with wantarray the outside context behavior with print, print scalar and a void call.

    For instance I doubted that scalar m// returns true or false (those identifiers don't exist in Perl), I thought it's the number of matches returned.

    But I was wrong: :)

    DB<23> $_="aaa" DB<24> print scalar m/a/ 1

    Cheers Rolf

    UPDATE: Forgot to mention, you can also check the prototype for most builtins:

    perl -e 'print prototype "CORE::push","\n"' \@@
    which is more complex than just void, list and scalar... check out perlsub for details.

    And some builtins (like map) have such a "rich" syntax that they can't be expressed with prototypes.

      For instance I doubted that scalar m// returns true or false (those identifiers don't exist in Perl), I thought it's the number of matches returned.

      But I was wrong: :)

      DB<23> $_="aaa" DB<24> print scalar m/a/ 1
      Anything in Perl is true or false. Or rather, ANYTHING is true but undef is false. 😋

      Like the relops, m//, s///, and y/// can all return the magical false value, that secret special value that nobody talks about:

      % perl -wle 'printf "got %d matches\n", scalar ANYTHING =~ /nothing/'
      got 0 matches
      So I shan’t, either. 😜
        > Or rather, ANYTHING is true but undef is false.

        Many things in Perl are evaluated to false in boolean context, not only undef.

        Cheers Rolf

Re: Easy Reference for Contexts
by dmn001 (Initiate) on Apr 14, 2011 at 23:17 UTC
    I sometimes refer to this:

    http://www.cs.tut.fi/~jkorpela/perl/regexp.html

    for regex reference.

    And the book Learning Perl is a great help too.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://899364]
Approved by philipbailey
Front-paged by philipbailey
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2024-04-18 21:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found