http://www.perlmonks.org?node_id=918571


in reply to trouble understanding code, and shift() w.o args

Why are those variables (%nu_hash and $sstr) empty? It is good programming practice to initialize variables. That way, you know for sure what value they contain. Both are used shortly after, but you noticed that. Since they are declared within the subroutine, they will disappear after the subroutine returns control to the main program. Your example is a short subroutine, but this is just good practice to get into.

When this subroutine is used, it probably looks something like this:

$returned_value = getXCharacterPatterns($var1, $var2);

Let's say $var1 = 1, $var2 = 2. When the subroutine runs, Perl will create the array @_ = [1,2]. The first shift will take the first element off the array, and return it. $str will now equal 1, and @_ = [2]. The second shift works similarly. $pl = 2 and @_ will now be empty.

Replies are listed 'Best First'.
Re^2: trouble understanding code, and shift() w.o args
by DanielM0412 (Acolyte) on Aug 04, 2011 at 15:55 UTC
    okay this definately helped, :-) but what if i want an additional filepath as one of the arguments in the subroutine? would it be somethin like this?
    $ret_value = getXCharacterPatterns($var1, $var2, $filepath2);
    wow, u have no idea how much that helped, thx a lot

      Yes, that's how you'd add a third argument. You would need to also add a third shift in the subroutine to use it.

      Perl's handling of parameters to subroutines is strange; every other language I have used requires the parameters be listed in the subroutine definition. I have often seen

      sub translate { my ($noun, $verb, $object) = @_; my $german = "$noun $object $verb"; return($german); }

      in order to document what the subroutine expects: 1) three arguments, 2) in the order noun, verb, object. Also, that would be less confusing to a novice Perl programmer because it explicitly names @_, instead of assuming you know about it. Which, of course, now you do.