On 17/03/2011 15:56, Chris Stinemetz wrote:

I'm trying to use file path for my file that I want to read but I am
getting the following error when trying to use strict.

Can't use string ("C://temp//PCMD") as a symbol ref while "strict
refs" in use at ./DOband.pl line 10.

Any help is greatly appreciated.

#!/usr/bin/perl

use warnings;
use strict;

my $filepath = "C://temp//PCMD";

You are getting confused with backward and forward slashes. Backward slashes are the proper delimiter for Windows file paths, and require escaping in strings with a second back slash. However Perl is kind and allows either forward or backward slashes to serve the same purpose, but a plain forward slash doesn't require escaping.

What you have written contains pairs of forward slashes which, luckily, is interpreted the same as a single slash, so ultimately your code does what it is supposed to.

You should either take advantage of Perl's leniency and write

  my $filepath = "C:/temp/PCMD";

or use single quotes (within which backslashes need escaping only if they appear as the final character) and write

  my $filepath = 'C:\temp\PCMD';

my $outfile  = "output.txt";


open ("$filepath") || die "ERROR: opening $filepath\n";

Except for old-fashioned and exotic syntax, a call to open requires three parameters:

- The variable to assign the open file handle to
- The open mode (usually read or write)
- The file path and name

Apart from this, it is very wrong to enclose a simple scalar variable in quotes. Doing so does have a purpose, but it is an esoteric one and is almost never what you want to do.

It is best to stick to the low-priority 'or' instead of '||' as the latter will do what you want only if you have put parentheses around the parameters to the open call.

You should always put the system variable $! into your die string, as it explains the reason for the failure. It is also a bad idea to terminate the die string with a newline, as it prevents die from displaying the source file and line number where the failure occurred.

Putting these together, your code should read

  open my $fh, '<', $filepath or die "ERROR opening $filepath: $!";

open (OUTFILE, ">  $outfile") || die "ERROR: opening $outfile\n";

Interesting that you have remembered to include a file handle and an open mode here! But the other points apply:

  open my $outfile, '>', $outfile or die "ERROR opening $outfile: $!";

I hope this helps you.

Rob

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to