Sherif Anchor
Sherif Anchor

Reputation: 3

How do I use a scalar variable in a perl file test operator?

I am in my first afternoon of perl and am having trouble figuring out what is going wrong with my script. It seems I am not using the file test operator properly, but I am not sure how I am using it incorrectly.

use v5.14;

print "what file would you like to find? ";
my $file = <STDIN>;
my $test = -e $file;
if ($test) {
print "File found";
}
else {
print "File not found";
}

I have also tried replacing lines 5 and 6 with just

if (-e $file) {

and line 6 with

if ($test == 1) {

with no luck.

Upvotes: 0

Views: 179

Answers (2)

Oliver
Oliver

Reputation: 31

http://perldoc.perl.org/functions/-X.html

use v5.14;

use warnings;
use strict;

print "what file would you like to find? ";
#chomp to remove new line
chomp my($filename = <STDIN>);

#test if exists but can still be an empty file
if (-e $filename) {
    print "File found\n";
} else {
        print "File not found\n";
}

Upvotes: 1

Mat
Mat

Reputation: 206699

The problem isn't the test, it's the contents of $file. The end-of-line is not stripped when you do $file = <STDIN>;, and chances are you don't have a file with an end-of-line in its filename.

chomp($file);

after reading it and you should be good to go.

Upvotes: 4

Related Questions