sweetblood has asked for the wisdom of the Perl Monks concerning the following question:

I'm writing a script that uses "format STDOUT" in two seperate functions. But when I run the script I get the following error:

Format STDOUT redefined at ...

This happens even if the functions are not called.
I've done some looking around to find the answer. I read the perldoc perlform but it didn't quite sink in. Apparently my head is more dense than the perldoc. I'm guessing I need to use select somehow, but I just can't figure it out.
The script and even these functions are quite long so I'll include something I just dummied up that produces the same error:

#!/usr/bin/perl -w use strict; my $foo = "FOO"; my $bar = "BAR"; my $foobar = "FOOBAR"; sub foo { format STDOUT = FOO BAR @<<<<<<< @<<<<<<< $foo, $bar . write; } sub foobar { format STDOUT = FOOBAR BAR @<<<<< @<<<<<<< $foobar, $bar . write; } foo() if ($ARGV[0] =~ /^foo$/i); foobar() if ($ARGV[0] =~ /^foobar$/i);

I know this example isn't pretty but I just slammed it together.

TIA

Replies are listed 'Best First'.
Re: "Format STDOUT redefined"
by Roy Johnson (Monsignor) on Dec 12, 2003 at 17:43 UTC
    format is a compile-time global declaration.You can declare formats of different names and use the $~ variable to pick which to write to in each subroutine.

    Or, as the Camel suggests, use Filehandle and call the format_name method on the handle as appropriate.


    The PerlMonk tr/// Advocate
Re: "Format STDOUT redefined"
by Paladin (Vicar) on Dec 12, 2003 at 17:40 UTC
    You can give your formats different names, and open FILEHANDLES with those names to STDOUT then use those names as parameters to write. ie:
    open FORM1, ">-" or die "Error: $!\n"; open FORM2, ">-" or die "Error: $!\n"; format FORM1 = FOO BAR @<<<<<<< @<<<<<<< $foo, $bar . format FORM2 = FOOBAR BAR @<<<<< @<<<<<<< $foobar, $bar . write FORM1; write FORM2;
Re: "Format STDOUT redefined"
by ysth (Canon) on Dec 12, 2003 at 18:33 UTC
    Since only one will be used, you could just wrap your formats in eval "". Or use IO::Handle or FileHandle, give the formats different names, and say STDOUT->format_name("whatever"); before the write (whatever will be qualified with the current package.)