Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to ignore elements in a list assignment?

Tags:

perl

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?

like image 830
Wes Avatar asked Oct 22 '25 05:10

Wes


2 Answers

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
like image 98
toolic Avatar answered Oct 24 '25 05:10

toolic


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.

like image 25
Bork Avatar answered Oct 24 '25 05:10

Bork



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!