Skip to content


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.

print reverse 1 .. 5;
print scalar reverse 1 .. 5;
print reverse 12345;
print scalar reverse 12345;

Posted in Programming.

Tagged with .


8 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. ll says

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

  2. Dave Cross says

    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 says

    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 says

    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 says

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

    • Dave Cross says

      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 says

    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.

Continuing the Discussion

  1. Three Short Announcements – Perl Hacks linked to this post on February 24, 2011

    [...] 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 [...]



Some HTML is OK

or, reply to this post via trackback.