Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

what does shift do?

by dev2000 (Sexton)
on May 19, 2002 at 19:58 UTC ( [id://167697]=perlquestion: print w/replies, xml ) Need Help??

dev2000 has asked for the wisdom of the Perl Monks concerning the following question:

I'm sorry to ask this basic question, but I'm just getting started with mod_perl...
my $r = shift; $r->send_http_header('text/plain'); $r->print("mod_perl rules!\n");
I see "shift" used all over in examples, but I don't know why. What exactly does it do?

Replies are listed 'Best First'.
Re: what does shift do?
by mt2k (Hermit) on May 19, 2002 at 20:21 UTC
    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.

    Example:

    #!/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" }
Re: what does shift do?
by cjf (Parson) on May 19, 2002 at 20:07 UTC

    See shift :-)

    Update: From perlfunc:shift...

    Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down.

    Is that what you're looking for, or have I missed the mark completely?

Re: what does shift do?
by dmmiller2k (Chaplain) on May 19, 2002 at 20:27 UTC
    shift applies to an array, as in, shift @a or, shift(@a). It removes the first (i.e., 0th) element from the array, shifting the remaining elements back by one (hence the name, I suppose), and returns the first element as its value.

    So, if you have an array, initialized like this:

    my @a = ( 'a', 'b', 'c'); my $x = shift @a;

    then after this code executes, $x will contain the scalar value, 'a', and @a will contain, ( 'b', 'c' ).

    In lexical scope (i.e., within a subroutine), shift by itself, without any arguments, implicitly acts upon the variable @_, which contains the subroutine's arguments.

    At file scope (i.e., outside of any subroutine), it implicitly operates instead upon @ARGV (also known as ::@ARGV, or main::@ARGV), which contains the command line parameters passed to the script.

    See the docs, "shift".

    dmm

    There are no stupid questions -- just stupid-making responses
      So, why exactly was it needed at all in my example?

      Wouldn't:
      send_http_header('text/plain'); print("mod_perl rules!\n");
      be identical? (guess I should try this, huh?)

      It didn't work... Undefined subroutine !

      P.S. the original example was the ENTIRE program, not within a subroutine, that's why I was so puzzled as to what was shifting (and why).

        sub greet { my $name = shift; print "Hello, $name\n"; } greet('dev2000');

        In mod_perl, with Apache::Registry, your script is cached in a sub, and that sub gets the Apache object as its argument. You could of course write this:

        $_[0]->send_http_header('text/plain'); $_[0]->print("mod_perl rules!\n");
        But it's easier to have a named variable for that, especially when you use other subs and your @_ gets overwritten.

        Back to the point, your script:
        my $r = shift; ...
        is wrapped in a sub so it can be cached:
        package Some::URL::Based::Package::Name;use Apache qw(exit);sub handle +r { #line 1 script.pl my $r = shift; ... }
        And suddenly, it all makes sense.

        - Yes, I reinvent wheels.
        - Spam: Visit eurotraQ.
        

        Because $r is being used as an object, by calling its send_http_header() and print() methods. Without the shift (I presume this is inside a subroutine), the object represented by the reference $r would never be referenced and the code would not work.

        P.S., without seeing the context in which your example lives, it I do not exactly know what kind of object $r is , but from its method names, I suspect it's one of the Http::XXX'en.

        dmm

        If you GIVE a man a fish you feed him for a day
        But,
        TEACH him to fish and you feed him for a lifetime
Re: what does shift do?
by dev2000 (Sexton) on May 19, 2002 at 21:12 UTC
    I think I'm starting to understand...

    Look what's inside of $r...
    Apache=SCALAR(0x87e40c0)
    If I'm running my scripts under Apache::Registry does that mean that they are not running at full mod_perl speed?
      Apache::Registry is one of the simplest ways to use mod_perl. It takes a CGI-like script from a CGI-program-like-file, and turns it into a specific subroutine invoked when a particular URL is requested.

      It's running at full mod_perl speed, but you'll find for more flexibility, you'll want to get away from the "persistent CGI" model and more towards "content handler" and "web application" models as you progress in your mod_perl knowledge.

      -- Randal L. Schwartz, Perl hacker

Re: what does shift do?
by hsweet (Pilgrim) on May 20, 2002 at 01:31 UTC
    I'm not sure of your context, but shift is just getting the first argument to a subroutine and passing it along to your variable. It's shifting off @_. It's a construct used a lot writing objects.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-03-29 14:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found