This blog no longer exists.
You will be redirected to something cool.

Wednesday, September 21, 2011

No, I Don't (Context in Subroutines)

Okay, so I was introduced with subroutines which seemed all fine and dandy. I was actually excited to finally be exposed to subroutines. However, it seriously baffles my mind. The subroutines... cake. Context with subroutines? I want to pull my hair out.

I read the chapter last night and it's the first time in the course where I didn't understand anything that was happening. I read on to see if I could piece it together, but alas I am at a wall. A brick one. Hopefully I'll get it after I muck through it again.

In other news, I went through my articles on HubPages and I either need to actually try to rank for the keywords which I've written articles around OR write more articles. I really don't feel like going around and grabbing up backlinks. That said, none of the articles on my list are anything I really feel like writing about. I'll have to find a way to raise the bar on my motivation when it comes to writing.


What sort of context do you mean? Are you referring to variable lexicality ( ie: my / our / local ), or "closure" behaviour ( ie: the property of subroutines that they can access variables in the same scope even once that containing scope no longer is visible to any other code )?

Or something else?


Ok, read a few other of your posts and think I see what you're asking, you're asking about the calling context of subs.

For the most part, calling context works lots like scalar vs list context. The "context" is merely forwarded to the sub's "return".


sub bar {
my @v = qw( a b c d );
return @v;
sub foo {
return bar();

my ( $x ) = foo();

Behaves exactly as if you'd done

my ( $x ) = bar();

and that behaves exactly as if you'd done

my @v = qw( a b c d );
my ( $x ) = @v;

( which discards b c d and assigns 'a' to $x.

Thats the basic gist of it.

There is an additional trick you can also do using the function 'wantarray' ( see perldoc -f wantarray ) which returns a value indicating what type of context its called in so you can provide different behaviours ( a vague resemblance in some ways to multi-method dispatch )

For instance, we could replace bar in the above with

sub bar {
if ( not wantarray ) {
my @v = qw( a b c d );
return @v;

and this would turn

my $x = foo() # foo is in scalar context here


foo() + 1

into a fatal exception.

Hope that helps.