Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Uninitialized value warning in subrutine

by olivierp (Hermit)
on Jan 29, 2005 at 09:18 UTC ( #426209=note: print w/ replies, xml ) Need Help??


in reply to Uninitialized value warning in subrutine

I assume you would like to access the last element of the implicit @_ array. Note that @_ and $_ are 2 different variables, as @var and $var are.
In a sub, @_ represents the arguments that you passed in, and this is what you should be accessing, whereas $_ is the "default" variable used/created in various looping constructs, the "default" match target , amongst others, as infor (@array){ print $_ if /hello world/i}
Your "Use of uninitialized value in substraction (-)" comes from trying to substract 1 from the $_ variable, which is undefined in the sub, when you actually would like to substract 1 from the number of items in @_
Here are 3 ways of achieving what you are looking for:

# Access directly the last element of the array sub queryDBI { my $query1 = "SELECT $_[2],$_[3],$_[-1] FROM " . $_[1]; return $query1; } print queryDBI(qw/first second third fourth fifth_and_last/),$/ x 2'
# In scalar context, @array returns the number of elements in contains +. # As @array indexes start at 0 (unless someone explicitly changes this + through $[), we substract 1 sub queryDBI { my $query1 = "SELECT $_[2],$_[3],$_[@_-1] FROM " . $_[1]; return $query1; } print queryDBI(qw/first second third fourth fifth_and_last/),$/ x 2'
# $#array returns the index of the last element of the array. sub queryDBI { my $query1 = "SELECT $_[2],$_[3],$_[$#_] FROM " . $_[1]; return $query1; } print queryDBI(qw/first second third fourth fifth_and_last/),$/ x 2'
For further info on predefined variables, as $_ and @_ check out perlvar
HTH
--
Olivier


Comment on Re: Uninitialized value warning in subrutine
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2014-10-01 00:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (386 votes), past polls