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];
Dada
  • 6,313
  • 7
  • 24
  • 43
  • 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;` – TLP May 17 '22 at 10:26

1 Answers1

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

Shawn
  • 47,241
  • 3
  • 26
  • 60
  • 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. – Shawn May 17 '22 at 05:05