tags:

views:

52

answers:

3

Hi all,

when I run the following script.pl script with no arguments:

./script.pl

I do not get the message No arg. Why? How to identify if $param is a null value or empty value, same as [ -z from ksh?

#!/usr/bin/perl
my $param = $ARGV[0];
if ($param = "") {
    print No arg;
} else {
    print arg: $param;
}
+4  A: 

Because it's not Perl. Where did you learn that syntax? So much is wrong with it.

  1. $param = "" assigns an empty string to $param, that's not what you want.

  2. null is spelled undef in Perl.

  3. To compare strings, use the eq operator.

  4. You must quote strings: print "No arg"

Much easier:

#!/usr/bin/perl
if (@ARGV) {
    print 'have parameters';
} else {
    print q{don't have parameters};
}
daxim
but if I have ARG1 and not ARG2 I get the don't have parameters?
lidia
I nearly made that same suggestion, but I'm guessing the OP wants to extend to handle different numbers of arguments, and then testing the length of @ARGV isn't quite so tidy.
Andy Mortimer
Just try it and see. When you pass any parameters on the command-line, `@ARGV` is filled with values and the program goes into the first branch.
daxim
can you give me example for that THX
lidia
why need to print q{don't have parameters}; and not print "don't have parameters" ??
lidia
@lidia: there is more than one way to do it.
Konerak
A: 

OK, it seems people found my previous answer mis-leading, so here's another try, more directly this time.

The test you're looking for is defined:

my $param = $ARGV[0];
if (defined $param) {
    print "arg: $param\n";
} else {
    print "No arg\n";
} 

If there weren't enough parameters to fill in $ARGV[0] (or other later elements) the value in that position will be undef, so the defined test will evaluate to false.

Andy Mortimer
A: 

Here is an example to illustrate it a bit better.

if( $#ARGV == -1 ){
    print "No arguments passed.\n";
} else if( $#ARGV == 0 ){
    print "One argument passed.\n";
} else {
    print $#ARGV +1 ."arguments passed.\n";
}

I like using "scalar @ARGV" as this represents number of elements in an array. $#ARGV, instead, is the index of last element in the array. This is why it is off by one. If $[ (this is a special variable that sets the starting index of Perl arrays.) was set to 1 and not 0 (the default), then $#ARGV would not be off by one for our purposes. I would not mess with $[ as it is a global. Changing may break a lot modules.

my $argument_count = scalar @ARGV;
if( $argument_count == 0 ){
    print "No arguments passed.\n";
} else if( $argument_count == 1 ){
    print "One argument passed.\n";
} else {
    print "$argument_count arguments passed.\n";
}
gdey