Interpreting arguments in Perl program.

Hello.
I'm new to Perl and I am not sure how to interpret command line arguments in the program. I am writing a program similar to the Unix utility 'tail' and need to check if first argument is '-1' ([dash]1) or any arbitrary number of lines to output. How would I write an 'if' statement to check for the dash (-) and a number? Checking for the dash is trivial below.

if ($ARGV[0] eq "-")
{
    print "I think it works\n";
}

How can I parse the dash with a number attached? Any numerical value?

Sample program run below:

File 'samp.txt' contains:
Hello World
This
Is
A
Test

-------
$tail.pl -3 samp.txt
Is
A
Test

Hi D2K,

Here an example of how you can check the input argument:

$ echo "-4" | perl -nE 'm/^-(\d+)$/ and say $1 or die qq|Bad argument\n|'
4
$ echo "+-4" | perl -nE 'm/^-(\d+)$/ and say $1 or die qq|Bad argument\n|'
Bad argument
$ echo "-42354" | perl -nE 'm/^-(\d+)$/ and say $1 or die qq|Bad argument\n|'
42354
$ echo "42354" | perl -nE 'm/^-(\d+)$/ and say $1 or die qq|Bad argument\n|'
Bad argument

Thanks for the comment.
When I tried this below (or I may not have done it right):

if ($ARGV[0] eq "m/^-(\d+)$/")
{
    print "I think it works\n";
}

It gives a compile error of unrecognized escaped character '\d'.

eq is for comparing strings. To check regular expression use =~ without double quotes:

if ($ARGV[0] =~ m/^-(\d+)$/) {  print "I think it works\n"; }
1 Like

I ended up using the substr() function. Thanks for the help. I will check that out later.