CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
how to open multiple file handles?

 



newbeeAllen
Novice

Nov 25, 2014, 10:35 PM

Post #1 of 2 (1709 views)
how to open multiple file handles? Can't Post

The code is as follows. I want to split a line into 2 parts if the pattern is found. Then write part1 to a file and part2 to another. How to do that? Thank you !


Code
#! usr/bin/perl -w  
use strict;

open MYHANDLE, "<PerlPractices.txt"
or die "cannot open file!";

my @lines=<MYHANDLE>;
my @text1;
my @text2;

my $line=shift @lines;

while ($line){
if($line=~/^mu_2/s){
my @parts= split /\s+/ , $line;
push @text1, $parts[0].="\n";
push @text2, $parts[1].="\n";
}
else{
push @text1, $line;
push @text2, $line;
}
$line=shift @lines;
}

close MYHANDLE;


Laurent_R
Veteran / Moderator

Nov 26, 2014, 12:27 AM

Post #2 of 2 (1708 views)
Re: [newbeeAllen] how to open multiple file handles? [In reply to] Can't Post

You just need to open two files for output:

Code
my $file1 = "file1.txt"; 
open my $FH1, ">", $file2 or die "cannot open $file1 $!";
my $file2 = "file2.txt";
open my $FH2, ">", $file2 or die "cannot open $file2 $!";

Then, later in your code, when reading the input file, something like this:

Code
if (some_condition) { 
print $FH1 $line;
} else {
print $FH2 $line;
}

Please take note of the more recent three-argument syntax for the open function and of the use of lexical filehandles (filehandle variables declared with "my"), this is widely considered in the Perl communauty as a better practice than the syntax you used for opening your input file.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives