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 in
for (@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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.