Perl Split Function - How to assign a specify array value to a variable in one line

Viewed 71

Is this a way of using a one-liner to assign an array value to a variable using the split function.

I have the following code. This works.

my @Fields = split(',',@_[0]);
my $Unit = @Fields[2];

Wondering if it could be written in one like the following, they are returning syntax errors.

my $Unit = split(',',@_[0])[2];

my $Unit = @(split(',',@_[0]))[2];
1 Answers

Your second one is very close. Drop that leading @:

my $Unit = (split(',', $_[0]))[2];

(Note $_[0] instead of the one-element array slice @_[0]... if you have use warnings; in effect like you should, that would give you one.)

Related