Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

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?



Comment on Placement of $~ or $FORMAT_NAME
Download Code
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
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (11)
As of 2015-12-01 17:07 GMT
Find Nodes?
    Voting Booth?

    My keyboard shows this many letters:

    Results (21 votes), past polls