Reputation: 313
I wish to modify one particular line in perl script :
@list = ([$tmp[0],$tmp[1],$tmp[2]]);
I have change it to this:
if( $input == 3 )
{
@list = ([$tmp[0],$tmp[1],$tmp[2]]);
}
if( $input == 2 )
{
@list = ([$tmp[0],$tmp[1]]);
}
if( $input == 1 )
{
@list = ([$tmp[0]]);
}
Above code works, but I would like it to works with $input
values up to 40 .
I try few different approaches but I am not able to code it in more elegant way, which really bother me.
Much appreciated any help with it.
Upvotes: 2
Views: 67
Reputation: 385590
The following does what you requested:
@list = [ @tmp[ 0 .. $input-1 ] ];
The following does what you want:
my @list = @tmp[ 0 .. $input-1 ];
You can also do the latter in-place very efficiently using the following:
splice(@tmp, $input);
Upvotes: 6
Reputation: 61512
You can use an array slice
, which will return a list of elements from the @tmp
array that you are interested in:
my @list = @tmp[0..$input-1];
The basic idea is that you copy the elements starting at index 0 to the maximum index you are interested in $input
.
Upvotes: 1