A Clockwork Orange
A Clockwork Orange

Reputation: 24793

Perl - Use of uninitialized value?

So I'm trying to run this code...

my $filePath = $ARGV['0'];
if ($filePath eq ""){
    print "Missing argument!";
}

It should check the first command line argument, and tell me if its empty, but it returns this error and I can not figure out why:

Use of uninitialized value $filePath in string eq at program.pl line 19.

What am I doing wrong?

Upvotes: 11

Views: 48165

Answers (4)

vol7ron
vol7ron

Reputation: 42099

Alternative answer is to set a default value if it is not defined:

my $filePath = $ARGV[0] // '';

Upvotes: 4

Caterham
Caterham

Reputation: 2301

Just check to see if $ARGV[0] is defined

#!/usr/bin/perl
use strict;
use warnings;

if(!defined $ARGV[0]){
    print "No FilePath Specified!\n";
}

This will print "No FilePath Specified!\n" if there was none passed command line.

The problem you are running into, is you are setting $filePath to an undefined value. Warnings is complaining because you've then tried to compare an undefined value to "". Warnings thinks that is worth telling you about.

I used my example to show a clean way of checking if something is defined, but technically for this, you could also just do:

if(!@ARGV){
    print "No FilePath Specified!\n";
}

Upvotes: 19

anydot
anydot

Reputation: 1539

EDIT: As @Andrew pointed out, that's not same, as it will fail with filename "0"

Also, instead of

if ((!defined $filePath) || ($filePath eq "")) { ...

as @Mat wrote. you can use simpler

if(!$filePath) { ...

which does exactly the same

Upvotes: 0

Mat
Mat

Reputation: 206689

Empty and uninitialized are not the same thing. You can check if a variable is initialized with the defined operator, like for example:

if ((!defined $filePath) || ($filePath eq "")) {
 # $filePath is either not initialized, or initialized but empty
 ...
}

I'm pretty sure you meant this:

my $filePath = $ARGV[0];

(without the quotes)

Upvotes: 9

Related Questions