in reply to Shift versus Sanity

I don't think shift is bad. I find myself using it in a lot of code, especially modules that I write for office use. In some subroutines, I find myself using 3-5 shifts. In one of my modules (Student::Server), I've done this:
sub usr_create { my $DC; Win32::NetAdmin::GetAnyDomainController('','CLC', $DC); my $obj = shift; my $usr_log_file = shift; my $params = shift; if ( $obj->usr_log($usr_log_file,$params) ) { return 0; } my $usr = $obj->_rand_user(); if ( not Win32::NetAdmin::UsersExist($DC,$usr) ) { $obj->usr_add($usr); } else { $obj->usr_create($usr_log_file,$params); } }
Most people would probably frown upon that usage, but I like it. If I only need one parameter (per variable), then it's much easier to avoid confusion about parameters. In the above sub, I expect an object, a filename, and an array ref (which contains the order of logging parameters). In other words, a call to usr_create would look like: $obj->usr_create('test.txt', [Last_Name, First_Name, State]); or even  $obj->usr_create('test.txt', $aref); shift'ing out the necessary parameters avoids silly things like having a user pass too many arguments to the sub. In that case, anything not shift'ed out is discarded.

Theodore Charles III
Network Administrator
Los Angeles Senior High
4650 W. Olympic Blvd.
Los Angeles, CA 90019
323-937-3210 ext. 224
perl -e "map{print++$_}split//,Mdbnr;"

Replies are listed 'Best First'.
Re^2: Shift versus Sanity
by tadman (Prior) on Apr 24, 2002 at 02:03 UTC
    This is one of those examples of things that bothers people, myself included. Three shifts, and no use of @_ to justify it, really. Instead, you could just declare them in a single my and be done with it, like:
    my ($obj, $usr_log_file, $params) = @_;
    Extra params passed by the user are discarded, as one would expect.

    The reason being shifty is annoying is because it can degenerate into nonsensical situations like this:
    sub foo { my $self = shift; my $foo = shift; $self->something($foo, "bar", shift, "shift", "foo"); my ($flob,$blarg,$kvetch) = (shift,shift); if ($kvetch = $flob->fnordicate($blarg)) { shift()->refnordicate($kvetch); } }
    What, exactly, are the parameters to this function? You have to read and understand the entire function before it becomes clear. If this were much larger, that could be very frustrating. Unfortunately, this fictional example is not too far fetched.
      "shift() doesn't confuse people. People confuse people."

      I agree that the example given would be nonsensical. However, if I saw it, I wouldn't blame shift(). I'd blame the programmer who abused it in that way.