Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: what does shift do?

by mt2k (Hermit)
on May 19, 2002 at 20:21 UTC ( #167705=note: print w/replies, xml ) Need Help??

in reply to what does shift do?

Also take a look at push, pop, and unshift.

These are also used (though not as often as shift).
Shift is used the most because it removes and returns the next item in an array. This is ideal for subroutines, where each call to shift() gets the next argument passed to the subroutine.


#!/usr/bin/perl use strict; &doIt("foo", "bar", "foobar"); sub doIt() { print shift, "\n"; #prints "foo" print shift, "\n"; #prints "bar" print shift, "\n"; #prints "foobar" }

Or, if you are demented in the head, you could use pop() and pass the arguments backwards:

#!/usr/bin/perl use strict; &doIt("foo", "bar", "foobar"); sub doIt() { print pop, "\n"; #prints "foobar" print pop, "\n"; #prints "bar" print pop, "\n"; #prints "foo" }

Though as far as subroutines go, I have been getting used to using 'named arguments' I suppose you might call them:

#!/usr/bin/perl use strict; &doIt(-first => "foo", -second => "bar", -third => "foobar"); sub doIt() { my %params = @_; #turns the passed arguments into an array print $params{'-first'}, "\n"; #prints "foo" print $params{'-second'}, "\n"; #prints "bar" print $params{'-third'}, "\n"; #prints "foobar" }

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (1)
As of 2022-10-07 05:29 GMT
Find Nodes?
    Voting Booth?
    My preferred way to holiday/vacation is:

    Results (29 votes). Check out past polls.