Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

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 ./test.pl line 32.

if called with ./test.pl -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?

Thanks,

loris

Comment on Placement of $~ or $FORMAT_NAME
Download Code
Re: Placement of $~ or $FORMAT_NAME
by JavaFan (Canon) on May 13, 2011 at 12:57 UTC
    From the documenation:
           HANDLE->format_name(EXPR)
           $FORMAT_NAME
           $~      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 $~.

      Thanks,

      loris

        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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://904656]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2014-07-26 10:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (175 votes), past polls