Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Placement of $~ or $FORMAT_NAME

by loris (Hermit)
on May 13, 2011 at 12:50 UTC ( #904656=perlquestion: print w/replies, xml ) Need Help??
loris has asked for the wisdom of the Perl Monks concerning the following question:

Dear All,

I know I should be using Perl6::Form and not struggling with Perl5 formats, but bear with me.

I want to print something formatted to the terminal or to a file. This is what I came up with:

#!/usr/bin/perl use strict; use warnings; use English qw( -no_match_vars ); use Getopt::Long; my $file; my $file_name = 'delete_me.txt'; GetOptions('file|f' => \$file, ); my $greeting = "Hello World!"; format BLAH = Greeting: @<<<<<<<<<<<<<<<< $greeting . $FORMAT_NAME = "BLAH"; my $fh; if (defined($file)) { open($fh,'>',$file_name) or die "Couldn't open $file_name for writ +ing: $!"; select($fh); } #$FORMAT_NAME = "BLAH"; write(); if (defined($file)) { close($fh); }

The code above produces the error

Undefined format "$fh" called at ./ line 32.

if called with ./ -f. If I uncomment the line before the write(), the data is written to the file.

Why is this and is there a better idiom for switching between filehandles when using formats?



Replies are listed 'Best First'.
Re: Placement of $~ or $FORMAT_NAME
by JavaFan (Canon) on May 13, 2011 at 12:57 UTC
    From the documenation:
           $~      The name of the current report format for the currently
                   selected output channel.  Default is the name of the
                   filehandle.  (Mnemonic: brother to $^.)
    You change the default filehandle after initially setting $FORMAT_NAME.

      Ah, so $~ isn't set for whichever filehandle is current, but just for the one that is current at the moment. If I change the filehandle with select() I also have to reset $~.



        Take care when switching: also $: and $^A can be affected and $%, $=, $-, and $^ will change on a select. The values might not always be reliable :) YMMV

        Enjoy, Have FUN! H.Merijn

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://904656]
Approved by ww
[Discipulus]: last hour of cb broken..

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2018-01-19 17:45 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (222 votes). Check out past polls.