Your skill will accomplishwhat the force of many cannot PerlMonks

### array slice?

 on Jan 31, 2014 at 14:18 UTC Need Help??
zeltus has asked for the wisdom of the Perl Monks concerning the following question:

I think my question is to do with array slices... but of course, I may be wrong!

```my @tarray = qw(one two three four five);
my (\$v2) = @tarray;
my \$v3 = (@tarray)[0];

Now, I am used to extracting slices using

```my \$v3 = (@tarray)[0];

in this case, extract the first element from @tarray and "give" it to \$v3...but upon examining some legacy code, I came across...

```my (\$v2) = @tarray;

...which does the same thing. But I can't work out why it works. Can someone please explain? Is it classifiable as a form or array slicing? I prefer my way for clarity, but are there any pros and cons for either method?

Thank you!

Replies are listed 'Best First'.
Re: array slice?
by Athanasius (Chancellor) on Jan 31, 2014 at 15:32 UTC

Hello zeltus,

```my \$v3 = (@tarray)[0];

looks a little odd. At the least, it’s unnecessarily complex: it says, “Take the elements of @tarray; treat them as a list; and return the first element of that list.” More straightforward to cut out the middle step and just say:

```my \$v3 = \$tarray[0];

If you do need a slice, an array slice is also more straightforward here than a list slice:

```my (\$v4, \$v5) = @tarray[0, 2];

See the FAQs:

Hope that helps,

 Athanasius <°(((>< contra mundum Iustus alius egestas vitae, eros Piratica,

Thank you!

Amongst other things, this is me trying to reduce the problem to the simplest demo code and losing the plot ever so slightly!

Reductio ad absurdum or somesuch... but no matter, I no where I am now

Bill

Re: array slice?
by zeltus (Beadle) on Jan 31, 2014 at 14:33 UTC

aah, I begin to see. After a lookaround, I found some info in perlsub: I see my question is a variant of

```my(\$key, \$value) = @_;

(copy a subroutines' parameters into named variables)

I guess this is clear enough... my fud was because my legacy code was dealing with just one parameter, making the code look a bit strange to me, is all

Re: array slice?
by kcott (Chancellor) on Feb 01, 2014 at 01:13 UTC

G'day zeltus,

I see ++Athanasius has provided feedback on the code you posted.

In addition to the FAQ links he posted, you might also like to look at perldata: Slices.

-- Ken

Create A New User
Node Status?
node history
Node Type: perlquestion [id://1072850]
Approved by Corion
help
Chatterbox?
 [Corion]: Viewing Tk Colours (Colors) by name has the list of all Tk colour names [choroba]: Aren't they the standard X colours? [ambrus]: choroba: that's not clear, since Tk runs on systems that don't even have X.

How do I use this? | Other CB clients
Other Users?
As of 2017-10-17 11:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My fridge is mostly full of:

Results (227 votes). Check out past polls.

Notices?