in reply to Several stupid questions about subs

Personally I never use local and as far as I am aware you shouldn't either! Perl does have a return statement!
my $var = foo(); sub foo { return 'bar'; } print $var;
what you get printed out is the word 'bar'. if you want to pass variables to a sub there are various ways;
my $var = foo('some_text_for_instance'); sub foo { my $text = $_[0]; return 'bar'; }
As far as I understand it $_[0], represents the first element of an array sent to the sub... so if you can do stuff like this;
my $var = foo($somevar,"some text",$somehashref); sub foo { my $variable = $_[0]; my $text = $_[1]; my $hashref = $_[2]; return $hashref->{'some_key'}; }
You can also capture the whole passed array;
sub foo { my @private_local_array = @_; #then lets return element 5 for some reason return $private_local_array[4]; }
There is also my $var = shift; but I'm not sure what that is or does or why one would want to use it.

Replies are listed 'Best First'.
Re^2: Several stupid questions about subs
by Anonymous Monk on Apr 13, 2011 at 17:28 UTC
    my @digitsOfPi = (3,1,4,1,5,9,2,6,5,3,5,9,'etc'); frobnicate('foo', 'bar', @digitsOfPi); sub frobnicate { my $fooString = shift; my $barString = shift @_; #more typing my @remainder = @_; print $remainder[0] == 3 ? 'yum' :'eew'; }

      my (...) = @_; is a very common way of getting args. I can't believe it wasn't mentioned.

      sub frobnicate { my ($foo, $bar, @remainder) = @_; print $remainder[0] == 3 ? 'yum' :'eew'; }
        Probably because the OP was asking about getting variables from the sub back to the scope from which it was called and this is the other way around.

        That code was in reply to the reply asking what my $var = shift; is all about