Context

This generated a lot of discussion in a training course that I ran this week so I thought it was worth sharing more widely.

I think you can say that you understand the concept of context in Perl if you know what these four statements will print and (more importantly) can explain why they don’t all produce the same thing.


Posted

in

by

Tags:

Comments

9 responses to “Context”

  1. ll Avatar
    ll

    Can you let us know the difference , three of them produce the same output

  2. Dave Cross Avatar

    Well, sure. I’ll be happy to post a full explanation at some point – perhaps if I leave it until next weekend that will give you all enough time to think about it.

    But in the meantime, if you want to work it out for yourself you could try reading the documentation for ‘reverse’ (and, of course, ‘scalar’ and ‘print’).

  3. hanekomu Avatar
    hanekomu

    Using single-digit numbers is a nice obfuscation. ๐Ÿ™‚

    @ll – Here’s a hint:

    print scalar reverse qw(foo bar baz);

    prints “zabraboof”.

  4. James Carman Avatar
    James Carman

    perldoc -f reverse

    I didn’t know reverse changed it’s return based on context. Learn something new every day.

  5. Ask Bjรธrn Hansen Avatar

    Yeah, I agree — it makes this question/quiz not so much “how does context work” but “what does ‘reverse’ do in scalar context?”

    1. Dave Cross Avatar

      Seems to me that there are two aspects to understanding context:

      1/ What context is this expression being evaluated in?
      2/ How do these operations and functions behave in this context?

      And this example nicely demonstrates that even if the first part is (sometimes) obvious, the only sure way to get an answer to the second question is to look in the documentation.

  6. Ian Avatar
    Ian

    The third statement prints a one-element list, which of course is the same backwards as it is forwards.

    N.B. Although I understood these examples, I still feel that I have yet to internalize Perl context to the extent that it has become second nature. This shows up especially in more-complex examples than the ones you use here.

  7. […] I was going to explain how the context examples in my last post worked. If you haven’t worked it out yet, I recommend a close read of the […]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.