2

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.

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I tested both, what I requested ( as you put it ) is what works in program I modify, thank you.
It's using an array to store a single value (a reference to the array that contains the actual values), which is silly.
(Unless, you add more to it later)
1

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.

Comments

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.