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

Hello everyone. I need some help with creating and writing to a new file.

I have a text file in the following format:
sku, itemname, itemdescription, price

I want to read each line, then write the contents of the line to a new file that is named sku.html

So for the following example source file: 123, soap, dove, $1.99
I want to save that line to a file named 123.html

I have the basics of how to open and read a file, and how to write to a new file. I just can't figure out how to name the new files dynamically after the sku field. Any suggestions are greatly appreciated. Thanks!

  • Comment on Writing to a new file with a dynamically created name

Replies are listed 'Best First'.
Re: Writing to a new file with a dynamically created name
by roboticus (Chancellor) on Feb 20, 2011 at 22:17 UTC
Re: Writing to a new file with a dynamically created name
by Monkomatic (Sexton) on Feb 21, 2011 at 00:22 UTC

    Hope this helps:

    $chunklookup = "Datafile.txt"; open(DGRAB, $chunklookup) || die ("Could not open $chunklookup (DATA T +O GRAB) \n"); while (<DGRAB>) {push(@datain, $_)};close DGRAB; foreach @datain {$currentline =$_; @linesplitfetch = split(/,/, $currentline); open (MYFILE6, '>@linesplitfetch[0].html')|| die ("Could not open @lin +esplitfetch[0].html \n"); print MYFILE6 "$currentline here ";close(MYFILE6); } # foreach @datain

      That code would be much better as:

      use Modern::Perl; use autodie; open my $in_fh, '<', 'Datafile.txt'; while (<$in_fh>) { my ($outfile, @extra) = split /,/, $_; open my $out_fh, '>', "$outfile.html"; print $out_fh @extra; }

      ... and you could even golf it further, but that's a decent balance of simplicity and clarity and safety.