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.

By Dave Cross

Dave Cross runs Magnum Solutions Ltd., a London Perl consultancy.

In 1998 he started London Perl Mongers, the first Perl Mongers group outside of Northern America.

He is the author of Data Munging with Perl and a co-author of Perl Template Toolkit.

9 replies on “Context”

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

Using single-digit numbers is a nice obfuscation. 🙂

@ll – Here’s a hint:

print scalar reverse qw(foo bar baz);

prints “zabraboof”.

perldoc -f reverse

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

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.

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

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