Novice Q: Can't use string ("X") as a symbol ref

Y

Yevgeniy K.

I have the following code to open a file:

use strict;

sub open_file {
my ($file, $FILE) = @_;
unless (open ($FILE, ">>$file")) { die "error msg\n" }
}

And at runtime I get: "Can't use string ("LIST") as a symbol ref while
"strict refs" in use"

Maybe my understanding of references is incorrect, but I fail to grasp
why this is a reference. I assign the value of local scalar variable
$FILE to the second argument passed to the subroutine, which in this
case happens to be "LIST"; then use that scalar var instead of a
literal to set the filehandle--what is the problem? Please advise!
Thanks in advance!
 
S

sln

I have the following code to open a file:

use strict;

sub open_file {
my ($file, $FILE) = @_;
unless (open ($FILE, ">>$file")) { die "error msg\n" }
}

And at runtime I get: "Can't use string ("LIST") as a symbol ref while
"strict refs" in use"

Maybe my understanding of references is incorrect, but I fail to grasp
why this is a reference. I assign the value of local scalar variable
$FILE to the second argument passed to the subroutine, which in this
case happens to be "LIST"; then use that scalar var instead of a
literal to set the filehandle--what is the problem? Please advise!
Thanks in advance!

Its all mucky stuff, barewords, symbols, filehandles.
Any scalar can be used in an open, it depends upon whats in the variable
and if "strict refs" are in effect.

These are some options. What's in the textfile.txt after you do the below?

my $FILE = "LIST";
open ($FILE, '>>', "textfile.txt") or die $!;
print $FILE "\"LIST\"\n";
close $FILE;

use strict;
use warnings;

$FILE = *LIST;
open ($FILE, '>>', "textfile.txt") or die $!;
print $FILE "*LIST\n";
close $FILE;

$FILE = \*LIST;
open ($FILE, '>>', "textfile.txt") or die $!;
print $FILE "\\*LIST\n";
close $FILE;

$FILE = undef;
open ($FILE, '>>', "textfile.txt") or die $!;
print $FILE "undef\n";
close $FILE;

my $FOO = $FILE;
open ($FOO, '>>', "textfile.txt") or die $!;
print $FOO "FOO = FILE\n";
close $FOO;

$FILE = "LIST";
open ($FILE, '>>', "textfile.txt") or die $!;
print $FILE "\"LIST\"\n";
close $FILE;

-sln
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,481
Members
44,900
Latest member
Nell636132

Latest Threads

Top