Brandon McCaig wrote:
On Thu, Oct 28, 2010 at 9:28 PM, Jeff Peng<pen...@nsbeta.info>  wrote:
You get the files from windows to un*x?
try the command 'dos2unix'.

^G is a bell character (\a). That's not a platform issue, AFAIK.
Anyway, in response to this thread I wrote Perl scripts that seem to
work as replacements for dos2unix and unix2dos.

dos2unix.pl:

#!/usr/bin/env perl

use strict;
use warnings;

use File::Copy "cp";
use File::Copy "mv";

That is usually written as:

use File::Copy qw/ cp mv /;

use takes a list after the module name.

use File::Temp qw{ tempfile };

if(@ARGV == 0)
{
     print STDERR "Usage: dos2unix.pl file...";

No newline at the end of the string?

     exit 1;
}

for my $in_fn (@ARGV)
{
     open my $in_fh, "<", $in_fn or die "Failed to open '$in_fn': $!";
     my($out_fh, $out_fn) = tempfile() or
             die "Failed to open temporary file: $!";

     while(my $line =<$in_fh>)

If this is run on DOS/Windows then Perl will automatically translate "^J^M" to newline.

     {
         $line =~ s/\cM//g;
         print { $out_fh } $line;
     }

     close $in_fh or die "Failed to close '$in_fn': $!";
     close $out_fh or die "Failed to close temporary file '$out_fn': $!";

     my $backup = "$in_fn.orig";

     die "Backup file '$backup' already exists! Aborting..." if -e $backup;

     cp $in_fn, "$backup" or die "Failed to backup '$in_fn': $!";
     mv $out_fn, $in_fn or die "Failed to replace '$in_fn': $!";
     unlink "$backup" or
             die "Failed to unlink backup file '$backup': $!";
}

__END__

Did you know that Perl has built-in idioms to handle multiple file manipulation:

#!/usr/bin/perl

use strict;
use warnings;

# :bytes in case this is run on DOS/Windows so that
# ^M doesn't get translated away by standard IO
use open ':bytes';

unless ( @ARGV ) {
    warn "Usage: dos2unix.pl file...";
    exit 1;
}

# In-place edit variable
# This has to be a non-empty string to work on DOS/Windows
$^I = $^O eq 'MSWin32' ? '.bak' : '';

while ( <> ) {
    tr/\cM//d;
    print;
}

__END__




John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction.                   -- Albert Einstein

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to