Reputation: 129
$k="1.3.6.1.4.1.1588.2.1.1.1.6.2.1.37.32";
@a= split('\.',$k);
print @a[-1]; # WORKS!
print (split '\.',$k)[-1]; # Fails: not proper syntax.`
I'd like to print the last element of a split without having to use an intermediary variable. Is there a way to do this? I'm using Perl 5.14.
Upvotes: 9
Views: 16625
Reputation: 480
rindex() split last position while index() split from first position found
print substr( $k, rindex($k, '.')+1 );
Upvotes: 1
Reputation: 54323
Perl is attributing the open parenthesis(
to the print function. The syntax error comes from that the print()
cannot be followed by [-1]
. Even if there is whitespace between print
and ()
. You need to prefix the parenthesis with a +
sign to force list context if you do not want to add parens to your print
.
print +(split'\.', $k)[-1];
If you are not using your syntax as the parameter to something that expects to have parens, it will also work the way you tried.
my $foo = (split '\.', $k)[-1];
print $foo;
Upvotes: 23