0

I need a Perl script on Windows which deletes the newline characters from a file and merges all the lines into one line and then writes into another file into the %temp% directory on a Windows system. For example, this script is to delete newlines and create a single line and write into another file in %TEMP%.

I have script which deletes the newlines but the output goes to STDOUT. I am not able to create a file in %TEMP% and redirect the output to that file.

Following is my script which is not working:

my $inFile = $ARGV[0];
$ENV{'TEMP'} = 'C:\\TEMP';

if ($inFile eq "") {
    print "Input file is missing\n";
    print "perl file_into_one_line.pl <input fil>\n";
    exit 0;
}

open(INFILE, "< $inFile") || die "$0, FEJL: can't open $inFile: $!";
foreach (<INFILE>) {
    chomp;
    if (eof()) {    # check for end of last file
        print "$_\n";
    } else {
        open FILE, ">$ENV{'TEMP'}//temp//tst.txt" or die;
        print FILE "${_}$separator";
    }
}

close(INFILE);
3
  • 1
    Please include the scripts you have written so far. Commented Apr 7, 2011 at 8:44
  • You can run your script like this: perl myscript.pl >%TEMP%/file.txt Commented Apr 7, 2011 at 8:46
  • inFile can be undef, so check !defined $inFile || $inFile eq "". Commented Apr 21, 2013 at 16:04

2 Answers 2

1

Note that %TEMP% is DOS syntax for accessing a environment variable. You can access the value of environment variables inside perl through the %ENV hash like so:

$ENV{k}

where k is a string expression that gives the name of the variable. Try this in your windows command line:

perl -e "print $ENV{'TEMP'};"

You should be able to do the rest from here on.

Sign up to request clarification or add additional context in comments.

Comments

0

The script should be:

my $separator = " "; # I think you should have this some where~~~

my $inFile = $ARGV[0];
$ENV{'TEMP'} = 'C:\\TEMP';

if ($inFile eq "") {
    print "Input file is missing\n";
    print "perl file_into_one_line.pl <input fil>\n";
    exit 0;
}

open(INFILE, "< $inFile") || die "$0, FEJL: can't open $inFile: $!";
open FILE, ">$ENV{'TEMP'}\\tst.txt" or die $!;
foreach (<INFILE>) {
    chomp;
    print FILE "${_}$separator";
}

print FILE "\n";

close(INFILE);
close(FILE);

1 Comment

After the ast line there is no $separator. So instead of the foreach loop I could suggest sg like print FILE join $separator, map {chomp; $_} <INFILE>;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.