Celeritas
Celeritas

Reputation: 15091

trying to read text file using Perl

I want the user to input a file name and have the program output the contents of the file.

I get 2x "Unquoted string may clash with future reserved word" and "Global symbol $filename requires explicit package name.

use strict;
use warnings;
print 'Enter file name: ';
my $fileName = <STDIN>;
chomp($fileName);
open(fh, $filename or die $!);

Also, why is file handle not a variable (actually depending on the example I've seen it a variable or not, like what I have here)?

Upvotes: 1

Views: 1829

Answers (5)

wholerabbit
wholerabbit

Reputation: 11567

All your problems are right here (and $filename vs. $fileName).

open(fh, $filename or die $!);

You want something more like

open (my $fh, '<', $filename) || die $!;

In the first case, the die condition is on $filename; it's equivalent to:

if (!$filename) { die $! }

But the second one is more like:

if (!open (my $fh, '<', $filename)) { die $! }

Although doing it this way (with if (!open)) is pointless unless you declare $fh with a more useful scope -- right now it's only visible inside the if block.

The second case implicitly covers the first case, since if $filename is undefined open() will fail with Use of uninitialized value $filename in open.

Upvotes: 5

Tiago Peczenyj
Tiago Peczenyj

Reputation: 4623

$fileName is different than $filename -- Perl is case sensitive!

Upvotes: 5

JRFerguson
JRFerguson

Reputation: 7526

You also asked why you sometimes see bareword filehandles (e.g.fh) versus scalar ones (e.g. $fh). The former is deprecated. Using declared, but otherwise undefined, scalar filehandles is called using an "indirect" filehandle. Perl auto-vivifies (creates) a reference to the file (handle) for you. Most importantly, as soon as the variable goes out-of-scope, and there are no other references to it, the filehandle is automatically closed and Perl's garbage collection can reap the memory used.

Upvotes: 3

Quentin
Quentin

Reputation: 944474

I get 2x "Unquoted string may clash with future reserved word" and

fh should be my $fh

"Global symbol $filename requires explicit package name.

$fileName and $filename are different variables. The second one hasn't be declared.

Upvotes: 4

Jonathan M
Jonathan M

Reputation: 17451

You need the dollar sign and the correct $fileName:

open(my $fh, '<', $fileName) or die $!;

Here's some helpful reference: http://perldoc.perl.org/functions/open.html

Upvotes: 2

Related Questions