Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: $dbh could not be passed to function unless another variable is also passed

by jcb (Parson)
on Aug 09, 2019 at 01:41 UTC ( [id://11104208]=note: print w/replies, xml ) Need Help??


in reply to $dbh could not be passed to function unless another variable is also passed

The idiom as I understand for extracting function arguments into lexicals is: my $var = shift;

Sample code:

use strict; use warnings; sub quux { my $foo = shift; my $bar = shift; my $baz = shift; print "FOO:$foo BAR:$bar BAZ:$baz\n"; } quux(1, 2, 'three'); quux(one => 2, 3); # illustrate "fat comma"

Sample output:

FOO:1 BAR:2 BAZ:three FOO:one BAR:2 BAZ:3

Generally, you should use one of these idioms near the very beginning of each sub to bring your arguments into lexicals. There is usually little difference between assigning @_ to a list of variables and using shift, but sometimes it can matter, particularly if you have additional arguments to process. You can also use splice on @_ to extract a group of arguments into a list of variables or an array, but this is a more advanced feature. Directly accessing elements of @_ is best limited to very short subs, with a comment listing the arguments nearby.

The "fat comma" is another neat Perl feature. You can think of it as quoting the previous word (there are some fairly complex rules for what gets quoted, but in most contexts it Just Works) and acting exactly like a normal comma in every other way. You will see it often in keyword arguments in many Perl modules. See the "Comma Operator" section in perlop for details.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2024-03-29 15:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found