user3217626
user3217626

Reputation: 129

How to get the last item of a split in Perl?

$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

Answers (3)

Ray Chakrit
Ray Chakrit

Reputation: 480

rindex() split last position while index() split from first position found

print substr( $k, rindex($k, '.')+1 );

Upvotes: 1

simbabque
simbabque

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

Kenosis
Kenosis

Reputation: 6204

Instead of creating a complete list and slicing it to get the last element, you could use a regex capture:

use strict;
use warnings;

my $k = "1.3.6.1.4.1.1588.2.1.1.1.6.2.1.37.32";
my ($last) = $k =~ /(\d+)$/;
print $last;

Output:

32

Upvotes: 10

Related Questions