Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

split

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.

like image 712
user3217626 Avatar asked Jan 27 '14 19:01

user3217626


People also ask

How do you split a string in Perl?

Perl | split () Function. split() is a string function in Perl which is used to split or you can say to cut a string into smaller sections or pieces. There are different criteria to split a string, like on a single character, a regular expression (pattern), a group of characters or on undefined value etc..

How to get the last item of a split string array?

Therefore, last is 'today?' . The array instance’s pop method removes the last element of an array in place and returns the removed element. Therefore, we can use it to get the last item of the split string array. And we get the same result as before for last .

What is limit in split function in Perl?

Limit: Limit is an optional parameter that was used in split function in Perl language. Using limit in split function we have restrict the number of output return using split function. How Split Function Works in Perl? Below is the working of split function in perl are as follows.

How do I split a string between two empty characters?

Between every two characters there is an empty string so splitting on an empty string will return the original string cut up to individual characters: $VAR1 = [ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' ]; By default split will exclude any fields at the end of the string that are empty.


1 Answers

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;
like image 184
simbabque Avatar answered Sep 28 '22 10:09

simbabque