Hadi Nounou Hadi Nounou - 2 months ago 4x
Perl Question

Applying (shift || '.') to a variable

I am currently learning perl and when I encountered a piece of code explainng how to traverse a directory tree using recursive subroutines. This is the code in question

use strict;
use warnings;
use 5.010;
my $path = shift || '.';

sub traverse {
my ($thing) = @_;

return if not -d $thing;
opendir my $dh, $thing or die;
while (my $sub = readdir $dh) {
next if $sub eq '.' or $sub eq '..';
say "$thing/$sub";
close $dh;

I understood the subroutine and how it works, however I did not understand this statement:
(my $path = shift || '.';)
I know that it is the variable that is passed to the subroutine, but I do not know what value it takes. Thanks in advance.


Outside of a subroutine, shift with no arguments does shift @ARGV, getting the first command-line argument.

The || operator returns the left side if the left side is truthy or the right side if the left side is falsy. So if the shift succeeded, $path probably gets set to the command-line argument. If @ARGV was empty, shift returns undef, so $path will get set to '.' instead.

Note this will do the wrong thing if for example you have a directory named "0" and try to run myscript.pl 0.