is there something more elegant to convert Dos to unix in subroutine?

A

Andrew

Ok, here is the next version, temp file stuff doesn't work on my CYGWIN

#
# Converts DOS to UNIX file
# if trim is true will trim leading and trailing spaces
#
sub toUnixFile {
my ($file, $trim) = @_;
-f $file || die "Can't open $file: $! \n";
my $temp_file = $file . ".tmp.$$.$^T";
move($file, $temp_file) || die "Can't move $file to $temp_file: $! \n";
open my $in, '<', "$temp_file" || die "Can't open $file: $! \n";
open my $out, '>', "$file" || die "Can't open $file: $! \n";
while(<$in>) {
s/[\r\n]+$//;
if ($trim eq "true") {
s/^\s+//;
s/\s+$//;
}
print $out "$_\n";
}
unlink $temp_file;
}


Uri Guttman said:
A> Thanks for constructive remarks, here is the fixed one, which, again,
A> works just fine :)

and looks ugly too!

A> sub toUnixFile {
A> my ($file, $trim) = @_;
A> -f $file || die "Can't open \"$file\": $! \n";

lose the \ there. use an alternative delimiter

A> my $temp_file = $file . ".tmp.$$.$^T";

use the File::Temp module

A> move($file, $temp_file);
A> local *in;
A> local *out;

gack! use lexical filehandles. and glob handles are upper case by tradition
A> open(in, "<$temp_file");
A> open(out, ">$file");

you check for the file with -f but not here? always check your open
calls for failures

A> while(<in>) {
A> chomp;
A> s/\r$//;

why the chomp AND s///? s/[\r\n]+$// would work anywhere.

A> if ($trim eq "true") {
A> s/^\s*//;
A> s/\s*$//;
A> unless ( -z $_ ) {

huh??!! what do you think -z does? this is perl, not shell.

and if i get your logic (which is coded incorrectly), you want to not
print lines that had only blanks. that means this is not a true dos2unix
program since that is not part of the typical spec for that.

A> print out "$_\n";
A> }
A> } else {
A> print out "$_\n";
A> }

redundant code always bothers me. if you used next you could have that
one print line for both cases.


and you still top post.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top