Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: trouble understanding code, and shift() w.o args

by GotToBTru (Friar)
on Aug 04, 2011 at 15:41 UTC ( #918571=note: print w/ replies, xml ) Need Help??


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.


Comment on Re: trouble understanding code, and shift() w.o args
Select or Download Code
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://918571]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2014-04-21 13:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (495 votes), past polls