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.

9 thoughts on “Context

  1. 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’).

  2. Using single-digit numbers is a nice obfuscation. :)

    @ll – Here’s a hint:

    print scalar reverse qw(foo bar baz);

    prints “zabraboof”.

  3. perldoc -f reverse

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

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

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

Leave a Reply