4

I am using a list assignment to assign tab-separated values to different variables, like so:

perl -E '(my $first, my $second, my $third) = split(/\t/, qq[a\tb\tc]); say $first; say $second; say $third;'
a
b
c

To ignore a value, I can assign it to a dummy variable:

perl -E '(my $first, my $dummy, my $third) = split(/\t/, qq[a\tb\tc]); say $first; say $third;'
a
c

I don't like having unused variables. Is there another way to do it?

3 Answers 3

6

You can use undef:

use warnings;
use strict;
use feature 'say';

(my $first, undef, my $third) = split(/\t/, qq[a\tb\tc]);
say $first; 
say $third;

Output:

a
c
4

You can use a list slice:

my ($first, $third) = ( split(/\t/, qq[a\tb\tc]) )[0,2];

Like with an array slice, e.g. @array[0,2], you can take a slice out of a list.

3
  • TMOWTDI, But I think I prefer making it explicit what I'm ignoring.
    – Wes
    Commented Feb 17, 2024 at 18:15
  • 4
    It's explicit that you are ignoring whatever is at index 1 :) Commented Feb 17, 2024 at 19:36
  • 1
    @Wes This is not less explicit.
    – Bork
    Commented Feb 17, 2024 at 21:44
3

In my declarations, undef serves as a placeholder. Therefore,

my ($first, undef, $third) = split(/\t/, qq[a\tb\tc]);

is a simpler alternative to

(my $first, undef, my $third) = split(/\t/, qq[a\tb\tc]);
3
  • 3
    You may wish to be more obvious about what you are doing. To the unobservant eye it just looks like you copied the first answer.
    – Bork
    Commented Feb 17, 2024 at 21:19
  • Thanks Bork, I meant it to be a comment to the accepted answer but I must have clicked incorrectly. Commented Feb 18, 2024 at 9:20
  • 1
    That's what I was thinking too, but hey, people did like it.
    – Bork
    Commented Feb 18, 2024 at 11:14

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.