Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "print $ARGV" alter the argument array in any way?

Here is the example:

$a = shift; 
$b = shift; 
push(@ARGV,$b); 
$c = <>; 

print "\$b: $b\n"; 
print "\$c: $c\n"; 
print "\$ARGV: $ARGV\n"; 
print "\@ARGV: @ARGV\n"; 

And the output:

$b: file1 
$c: dir3 

$ARGV: file2 
@ARGV: file3 file1 

I don't understand what exactly is happening when printing $ARGV without any index. Does it print the first argument and then remove it from the array? Because I thought after all the statements the array becomes:

file2 file3 file1

Invocation:

perl port.pl -axt file1 file2 file3 

file1 contains the lines:

dir1 
dir2 

file2:

dir3 
dir4 
dir5 

file3:

dir6 
dir7
like image 517
MeesterMarcus Avatar asked Dec 05 '22 08:12

MeesterMarcus


2 Answers

Greg has quoted the appropriate documentation, so here's a quick rundown of what happens

$a = shift;                 # "-axt" is removed from @ARGV and assigned to $a
$b = shift;                 # "file1" likewise
push(@ARGV,$b);             # "file1" inserted at end of @ARGV
$c = <>;                    # "file2" is removed from @ARGV, and its file
                            # handle opened, the first line of file2 is read

When the file handle for "file2" is opened, it sets the file name in $ARGV. As Greg mentioned, @ARGV and $ARGV are completely different variables.

The internal workings of the diamond operator <> is probably what is confusing you here, in that it does an approximate $ARGV = shift @ARGV

like image 56
TLP Avatar answered Dec 06 '22 20:12

TLP


In Perl, $ARGV and @ARGV are completely different. From perlvar:

$ARGV

Contains the name of the current file when reading from <>.

@ARGV

The array @ARGV contains the command-line arguments intended for the script. $#ARGV is generally the number of arguments minus one, because $ARGV[0] is the first argument, not the program's command name itself. See $0 for the command name.

like image 30
Greg Hewgill Avatar answered Dec 06 '22 22:12

Greg Hewgill