Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Dealing with Lists and Arrays

by talexb (Chancellor)
on Nov 11, 2002 at 14:43 UTC ( [id://211923]=note: print w/replies, xml ) Need Help??


in reply to Dealing with Lists and Arrays

I'm not sure that shift and unshift are so amazingly unique. After all, it's possible to simulate their behaviour with push and pop

Hmm, after tinkering quickly with some code, this is all I could come up with.

#!/usr/bin/perl -w my @data = qw/1 2 3 4 5/; print "Data is " . join ( ":", @data ) . "\n"; @data = reverse @data; my $foo = pop @data; @data = reverse @data; print "Data is " . join ( ":", @data ) . "\n"; @data = reverse @data; push ( @data, 17 ); @data = reverse @data; print "Data is " . join ( ":", @data ) . "\n";

So maybe shift and unshift are useful after all. Is there an easier way to simulate the behaviour that I've missed?

--t. alex
but my friends call me T.

Replies are listed 'Best First'.
Re: Re: Dealing with Lists and Arrays
by gjb (Vicar) on Nov 11, 2002 at 15:01 UTC

    It's not only a matter of merely simulating the behavior of shift and unshift, it may have a lot to do with execution efficiency since a reverse is an expensive operation. It involves creating a new list and populating it with the elements of the original in O(n) time (n = length of the list).

    A shift is typically O(1) time since it involves just taking out the first element of which you have the address anyway -- it's the start of the list -- and making the second element the first. The same holds for unshift which is a simple insertion at the beginning of the list.

    So for reasons of efficiency, you really want shift and unshift, not only to make code look more elegant.

    Hope this helps, -gjb-

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2024-04-25 19:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found