octopusgrabbus
octopusgrabbus

Reputation: 10685

Why is $#ARGV 0?

I've been searching through Perl resources, and I could not see where I am going wrong. I am pretty sure I'm missing something obvious, because when I assign

my $gArgc = $#ARGV;

but call my program perl pkTkPtBdTkNo.pl test.txt

$#ARGV is equal to 0, and I can't figure out why.

#! /usr/bin/perl -w

use strict;

my $gArgc = $#ARGV;
my $input_line;
my $bad_input;

print($gArgc);
die ("Usage pkTkPtBdTkNo.pl input-line")
    if(0 == $gArgc);

$input_line = $ARGV[0];
$bad_input = ($input_line =~ /\"\d+\D+\d*\",/);
print($bad_input); 

Upvotes: 5

Views: 7395

Answers (4)

xxfelixxx
xxfelixxx

Reputation: 6592

You could try:

@ARGV or die "Usage pkTkPtBdTkNo.pl input-line"

I find that avoiding the $#array_name syntax entirely improves readability greatly, since here perl will turn @ARGV into a scalar (with value 0) automatically.

Upvotes: 0

pkm
pkm

Reputation: 2783

The variable $#ARGV is the subscript of the last element of the @ARGV array, and because the array is zero-based, the number of arguments given on the command line is $#ARGV + 1.

Upvotes: 1

atk
atk

Reputation: 9314

From man perlintro:

The special variable $#array tells you the index of the last element of an array: ... You might be tempted to use $#array + 1 to tell you how many items there are in an array. Don't bother. As it happens, using @array where Perl expects to find a scalar value ("in scalar context") will give you the number of elements in the array:

So, if you pass 0 arguments, $#ARGV will be -1, since there are no elements in the array. If you pass 1 argument (as in your example), $#ARGV will be 0.

Upvotes: 10

mpapec
mpapec

Reputation: 50637

This should be always true, $#ARGV+1 == @ARGV as $#ARGV is last index of @ARGV array.

Upvotes: 2

Related Questions