1

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
  • 1
    You should use a scalar sigil when referring to an array slice of 1 element: my $unit = $fields[2]. Same with split(',',$_[0]). When using @_, it is better to copy the value to avoid changing it. E.g. my $arg = shift; my @fields = split ',', $arg; Commented May 17, 2022 at 10:26

1 Answer 1

3

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

If you have a lot of fields, you might consider (split(',', $_[0], 4))[2] to avoid it returning a longer list than is needed. What would normally be the 4th, 5th, 6th, etc. elements are all part of the 4th one with that length modifier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.