Charlie Farinella wrote:
On Wednesday 24 December 2008, Mr. Shawn H. Corey wrote:
On Wed, 2008-12-24 at 13:16 -0500, Charlie Farinella wrote:
I need to read in a file of 200 lines and print each out to a separate file.

I've been stumbling with this, but I don't know how to name each
outfile
individually. I was hoping to see 200 files named tx1 - tx200, but instead I get tx1234..................... for 123 files and then it
dies.
Help?

#!/usr/bin/perl

use strict;
use warnings;

my $i = 0;
my $outfile = "tx";

open( my $infile_fh, '<', "speed_test.csv" ) or die "could not open
speed_test.csv: $!\n";
# You should always test an open

        while( <$infile_fh> ) {
                my $file = $outfile . ( ++ $i );
open( my $out_fh, '>', $file ) or die "could not open
$file: $!\n";
                print $out_fh or die "could not print to $file: \n";
# prints $_ by default, $_ has a newline since it hasn't
been chomp'ed
                close $out_fh or die "could not close $file: $!\n"
# You should always test prints and closes except for
STDOUT and STDERR
        }

This worked great, thank you. I had to modify the print line to include $_, for whatever reason it created blank files as written.

That is because perl interprets the line:

print $out_fh;

as "print the string in $out_fh to the filehandle STDOUT" instead of "print the string in $_ to the filehandle $out_fh". You should have got something like GLOB(0x8152c28) printed on standard output.


I changed it to:

print $out_fh "$_" or die "could not print to $file: \n"

You don't have to quote the string in $_, it is already a string. And don't forget the error message in $!.

print $out_fh $_ or die "could not print to $file: $!\n";



John
--
Those people who think they know everything are a great
annoyance to those of us who do.        -- Isaac Asimov

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to