problem with perl input

Started by
2 comments, last by Cosmic314 11 years ago

hi, I'm having trouble running a perl script in both windows 7 and ubuntu

in windows when I try to run it it states the input file is specified twice

in ubuntu it claims it can't find the input file to open even though its in the same directory as the pl file I'm running.

here is the code up to the error point which occurs around the system function.

#!/usr/bin/perl

use strict;

use warnings;



use File::Spec;





my $inputFile = $ARGV[0];

my $backgroudFile = $ARGV[1];



#get name of the tester file and set it as the current working directory

my ($inputFileVolume,$inputFileDir,$name) = File::Spec->splitpath($inputFile);

my @workingDirArr = ($inputFileVolume,$inputFileDir);

my $workingDir = File::Spec->catdir(@workingDirArr);

chdir $workingDir or die "$0 failed to chdir to working dir $workingDir";



system ("sort -k 1,1 -k 4n -T $workingDir $name >tempLoc_$name")==0 or die "$0 failed to sort $name";

open (NAM, "tempLoc_$name") or die "$0 failed to open file tempLoc_$name";
Advertisement

In Windows there is no '-k' option for your sort system call. Sort interprets '-k' as the name of a file. Since you specify it twice this is why you get the error.

In Windows there is no '-k' option for your sort system call. Sort interprets '-k' as the name of a file. Since you specify it twice this is why you get the error.

What is a windows way to replicate the same functionality of the line?
Thanks

Unfortunately the Windows 'sort' program is quite limited. I'm no expert on the OS commands so I don't know if there is a substitute for it.

However, you could do the sort yourself inside of Perl. Open the file that you want to sort, store it in an array in memory, run it through a sort routine and store it in a new file.


open(RAW_INPUT,"<".$name) || die("Failed to open '".$name."'");
open(SORTED_OUTPUT,">tempLoc_".$name) || die("Failed to create 'tempLoc_".$name."'");

my (@raw_input) = ();  my ($line);

while($line = <RAW_INPUT>) { push(@raw_input,$line); }

my ($element);

foreach $element (sort @raw_input) { print(SORTED_OUTPUT $element); }

close(RAW_INPUT);
close(SORTED_OUTPUT);

If you want to customize the sort routine you'll need to change the sort line to something like:


foreach $element (sort numerically(@raw_input)) ...


sub numerically {
   $a<=>$b;
}

# The sorted lamba uses $a and $b as the comparators.  You can write code to make a
# customized sorter.  Here I choose to sort numerically which overrides Perl's default
# of alpha-numeric.

This topic is closed to new replies.

Advertisement