6

What's the purpose of the following two lines of perl??

my $host = shift || 'localhost';
my $port = shift || 200;

That should return localhost and port 10. What is the shift keyword??

Marco A.
  • 43,032
  • 26
  • 132
  • 246

5 Answers5

10

The first line shifts from either @_ or @ARGV (depending on where you are in the code), or in the absence of any contents in @_/@ARGV, assigns localhost to $host.

The second one should be self-explanatory now.

Have a look at the shift documentation for details.

Daniel Böhmer
  • 14,463
  • 5
  • 36
  • 46
DavidO
  • 13,812
  • 3
  • 38
  • 66
6

What this piece of code is, is a way to provide default values for $host and $port. It will typically be at the start of a script or a subroutine, and take values from @ARGV and @_ respectively.

That should return localhost and port 10.

No, the || operator is a short circuiting OR, which means that if the LHS operand returns a true value, the RHS operand is ignored. Basically, it means this (and ONLY this): "choose the left hand side value if it is true, otherwise choose the right hand side value."

shift ARRAY will return the first value of ARRAY, or:

If ARRAY is omitted, shifts the @_ array within the lexical scope of subroutines and formats, and the @ARGV array outside a subroutine and also within the lexical scopes established by the eval STRING , BEGIN {} , INIT {} , CHECK {} , UNITCHECK {} and END {} constructs.

Quoted from http://perldoc.perl.org/functions/shift.html

Also, of course, shift removes the value from the array that is shifted. Therefore you can have two shift in a row like this, for very convenient argument handling.

TLP
  • 66,756
  • 10
  • 92
  • 149
3

If no argument is provided, shift will shift @ARGV outside a subroutine and @_ inside a subroutine – that is the argument array passed to either the main program or the subroutine.

In your case, $host is assigned the first element of @ARGV (or @_, if the code is inside a sub) or 'localhost', if the element is false.

This is a very common Perl idiom.

Ricardo Branco
  • 5,740
  • 1
  • 21
  • 31
i-blis
  • 3,149
  • 24
  • 31
2

shift return the first element of an array and removes it from the array. Like pop, but from the other end.

Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
2

If you use shift, always put the array on it. I've seen experience Perl programmers forget that outside a subroutine, shift works on @ARGV. The more things a programmer has to remember at the same time, the more likely he is to make an error.

shawnhcorey
  • 3,545
  • 1
  • 15
  • 17