Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: why can't I shift a split? (List vs Array)

by LanX (Saint)
on Aug 25, 2022 at 23:25 UTC ( [id://11146432]=note: print w/replies, xml ) Need Help??


in reply to why can't I shift a split?

The fundamental problem here is that lists and arrays are two different things. That's a FAQ

Lists are temporary data sequences which can't be changed!

But Arrays are variable(s) with @sigils and they are changed.

Shift can only operate on arrays, because they are shortened afterwards.

Once you've understood this...

> why can't I shift a split?

Because split returns a list!

Unless you assign it to an array it can't be shifted.

Addendum

Others have shown solutions with (lists)[slices] which work similar to @array[slices] . That's only possible because a slice doesn't change its object, unlike shift.

Further reading

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^2: why can't I shift a split? (List vs Array)
by misterperl (Pilgrim) on Aug 26, 2022 at 14:07 UTC
    Rolf yes, I know that- but it should be EZ to coerce a list into an array?
      > should be EZ to coerce a list into an array

      sure:

      DB<2> p shift @{[42..59]} 42

      or

      DB<3> $shift = sub { shift @{$_[0]} } DB<4> p [42..59]->$shift 42

      but it doesn't make sense since the resulting shortened array is destroyed right away.

      Using a list slice is the logical° and easiest approach, without wasting operations.

      DB<5> p (42..59)[0] 42

      compare an array slice which wastes resources again, by allocating an array in memory which is destroyed again.

      DB<6> p [42..59]->[0] 42

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery

      °) and "implementing" pop list is symmetrical (42..59)[-1]

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11146432]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2024-04-20 00:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found