Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

how can i use one handle for multifple files

by Anonymous Monk
on May 15, 2003 at 10:52 UTC ( [id://258352]=perlquestion: print w/replies, xml ) Need Help??

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

Hi Monks,I have to write lot of data to a file but during this I check for a condition and If I satisfy that condition I have to write that specific block of code in separate file,How do I do this ?
$outFile = "tmp.txt"; $outFile1 = "tmpo.txt"; open FILE, "> $outFile" or die "Cannot open file: $!"; open TEMPFILE, "> $outFile1" or die "Cannot open file: $!"; $test = "TRUE"; printf FILE "\t%s", "connect("; printf FILE "\t%s", "parameter("; .. .. #100 lines of similar code here .. if($test =~ /\bTRUE\b/){ printf FILE "\t%s", "connect("; printf FILE "\t%s", "parameter("; .. .. #100 lines of similar code here .. }elsif($test =~ /\bFALSE\b/){ printf TEMPFILE "\t%s", "connect("; printf TEMPFILE "\t%s", "parameter("; .. .. #100 lines of same code here .. }
So you see there is lot of repetition.Is there any way so that I just make the handle point to other file ? something like this :
$outFile = "tmp.txt"; $outFile1 = "tmpo.txt"; open FILE, "> $outFile" or die "Cannot open file: $!"; $test = "TRUE"; printf FILE "\t%s", "connect("; .. .. #100 lines of similar code here .. if($test =~ /\bTRUE\b/){ FILE = $outfile; }elsif ($test =~ /\bFALSE\b/){ FILE = $outfile1; } printf FILE "\t%s", "connect("; printf FILE "\t%s", "parameter("; .. .. #100 lines of similar code here .. }

Replies are listed 'Best First'.
Re: how can i use one handle for multifple files
by fruiture (Curate) on May 15, 2003 at 11:09 UTC

    Yep, you can keep a filehandle in a scalar at any time:

    open my $fh1,'<', $file1 or die ...; open my $fh2,'<', $file2 or die ...; my $fh = $fh1; print $fh ...; if( some_condition ){ $fh = $fh2; } print $fh .... close $fh1; close $fh2;
    --
    http://fruiture.de
      The other benefit here, is that scalars can go out of scope, while file handles can't.. which can be very advantageous in some cases, because it provides for automatic cleanup so you don't have to close your filehandles explicitly in subs and blocks.
        File handles can go out of scope, if you use localized typeglobs.
        { local *FH; open FH, ">output.txt" or die "Can't write to file: $!"; print FH "Anything...\n"; printf STDERR "fileno for FH: %d\n", fileno(FH); } # ... open FH2, ">output2.txt" or die "Can't write to file: $!"; printf STDERR "fileno for FH2: %d\n", fileno(FH2);
        The file handle will be closed when the block is exited. It is extremely likely that you'll see the same value for fileno() for both handles... (for this as a script, I expect to see the value 3) indicating that the first one was released, thus, the handle got closed.
      You can implify your code if you put your filehandles into a hash. The condition was a test for a word (TRUE or FALSE) so the hash would be:
      $fh{'TRUE'}=$fh1; $fh{'FALSE'}=$fh2;
      and the print woud simply be: print $fh{$test} "..." Update: Thanks to BrowserUK (see below)!
      print { $fh{$test} } "..."
        No, that will not work - You cannot print directly to a file handle stored in anything other than a scalar because of the typeglob nature of file handles. Your code would return the following error as a result of the hash entry being interpreted as the first element of a list argument to the print function:

        String found where operator expected at test.perl line 10, near "} "te +st\n"" (Missing operator before "test\n"?) syntax error at test.perl line 10, near "} "test\n"" Execution of test.perl aborted due to compilation errors.

         

        perl -le 'print+unpack("N",pack("B32","00000000000000000000001001011001"))'

Re: how can i use one handle for multifple files
by jaa (Friar) on May 15, 2003 at 11:18 UTC

    Lots of things you could do differently, depending on where you want to go today!

    If I read your example correctly, you print a whole lot of stuff into FILE and then more of the same stuff to either FILE or TEMPFILE? This is probably not what you really are trying to do?

    FileHandle is a good way of working with filehandles 8-)

    Subs are a good way of organising lots of repeated lines of code

    You can pass parameters to subs to make them behave differently - for example:

    use strict; use FileHandle; my $outFile = "tmp.txt"; my $outFile1 = "tmpo.txt"; my $fhOut = FileHandle->new(">$outFile") or die "Cannot open file $ou +tFile: $!"; my $fhTemp = FileHandle->new(">$outFile1") or die "Cannot open file $o +utFile1: $!"; my $test = "TRUE"; saveStuff( $fhOut ); if($test =~ /\bTRUE\b/){ saveStuff( $fhOut ); }elsif($test =~ /\bFALSE\b/){ saveStuff( $fhTemp ); } $fhOut->close(); $fhTemp->close(); sub saveStuff { my $fh = shift; my ( @things ) = qw( apples pears peaches cream ); # You can use join() to add tabs between all the things you # are printing rather than printf $fh->print( join("\t", @things ) . "\n"); #100 lines of similar code here... }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-04-24 01:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found