Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re^2: Printing to a File from Sub

by PyrexKidd (Monk)
on Aug 27, 2010 at 22:56 UTC ( [id://857784]=note: print w/replies, xml ) Need Help??


in reply to Re: Printing to a File from Sub
in thread Printing to a File from Sub

here is code I am trying to use:

#!/usr/bin/perl use strict; use warnings; open my $fhout, '>', "./test_out.file" || die "$!"; &test_print($fhout); sub test_print{ my $fhout = @_; print {$fhout} "this is a test\n"; } close $fhout;

and here is the error message I keep getting:

~$ perl test_write.pl Can't use string ("1") as a symbol ref while "strict refs" in use at t +est_write.pl line 11.
What is going on here? am I just missing something? Thanks for the assist.

Replies are listed 'Best First'.
Re^3: Printing to a File from Sub
by choroba (Cardinal) on Aug 30, 2010 at 16:47 UTC
    You should either use
    open my $fhout, '>', "./test_out.file" or die "$!";
    or
    open (my $fhout, '>', "./test_out.file") || die "$!";
    . The code you posted is parsed as
    open (my $fhout, '>', ("./test_out.file" || die "$!"));
    which is definitely not what you want.

    To avoid the error you reported, though, use

    my ($fhout) = @_;
    or
    my $fhout = shift;
    Also note that the ampersand sign & is not needed when calling a sub (see perlsub).

Re^3: Printing to a File from Sub
by pemungkah (Priest) on Aug 29, 2010 at 00:50 UTC
    Putting the filehandle in parens told Perl that it is the argument to print, and so you wanted to print it to STDOUT - which is not what you wanted. You wanted to say
    print $fhout "this is a test\n";
    It should also be noted that the variable $fhout is actually still in scope in your subroutine, so you technically could just use it. It is, however, better practice to pass it in.

    Edit: choroba is correct as s/he notes below. I did mistake the curlies for parens.

      Not true. The problem is $fhout contains the number of elements in @_, not the filehandle. The syntax print {$fh} "out" is even recommended in PBP.
      Yes, those aren't parens, they are squiggle brackets, easy mistake to make with the right font and font size.

                      - Ant
                      - Some of my best work - (1 2 3)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://857784]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2024-03-29 02:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found