Perl system command output to files

August 8, 2009 at 11:31:30
Specs: Windows XP

I'm having trouble creating files when iterating through a list using a "foreach" loop. i.e. I have a file, target.txt, that lists hostnames which contains:


I have a perl script that iterates through this file, and for each hostname in the list, creates a file called host[number].txt and writes text to the file. So I would theoretically have host1.txt, host2.txt, and host3.txt, all with the same text in them, at the end of the run.

The problem is that the file is only being created for the very last hostname in the list.

Here's my code:

$TARGET = "targethostnames.txt";
open (TARGET) or die("Could not open file.");
foreach $line (<TARGET>) {

open (OUTFILE, ">>SW-$line.txt");
print OUTFILE "what the";
close (OUTFILE);

close (TARGET);

I've been at this for a while but can't figure out how to create a file for each hostname. Anybody have any ideas?

Thank you in advance,

Rakesh T.

See More: Perl system command output to files

Report •

August 8, 2009 at 12:53:19
I suspect that this is for a homework assignment, so I won't provide the complete solution, but I will guide you.

First, every Perl script you write should include the strict and warnings pragmas which will point out lots of mistakes that can be difficult to troubleshoot. So, add these two lines near the top of the script.

use strict;
use warnings;

The strict pragma forces you to declare your vars. So to declare $TARGET as a lexical var, you'd use the my keyword.

my $TARGET = "targethostnames.txt";

Now, also due to the strict pragma, the open call you have will no longer work as written. You need to specify the filename.
See: perldoc -f open

Now we're getting to the cause of your problem, which is 2 fold and I'm finding it hard to guide you here without providing the solution.

You never (or maybe I should say almost never) want to use a foreach loop to process the data coming from a filehandle. Instead, you should use a "while loop".

Now, each line in the file has a line terminator which needs to be stripped off. That is done with the chomp function.

Report •

August 9, 2009 at 19:52:43
Thank You, I got it working once I used your advice. Here's the code I went with:

use Config::Tiny;
use strict;
use warnings;

my $TARGET = "targethostnames.txt";
open (TARGET, "<", "targethostnames.txt") or die("Could not open file.");

while (my $text = <TARGET>) {

my $OUTFILE = "SW-$text.txt";
open (OUTFILE, ">", "SW-$text.txt");
print OUTFILE "whatthe";
close (OUTFILE);

close (TARGET);

Report •

Related Solutions

Ask Question