$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.
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..
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 .
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With