Some issues with your effort
- the shebang is not an absolute path
- not using strict/warnings, Read this if you want to cut your development time in half!
- you're using <STDIN> instead of @ARGV (as in perl myprogram.pl)
- you're reading from FILEHANDLE but your printing to STDOUT
- you're using FILEHANDLE instead of $filehandle
- your regular expression is case sensitive and it doesn't match your sample data
The general steps for editing a are
- read from original-file
- modify data
- write to new-file
- rename new-file to original-file
So you might write that as
#!/usr/bin/perl --
use strict; use warnings;
use autodie 2.1001;
use File::Temp qw/ tempfile /;
use File::Copy qw/ move /;
use autodie qw/ move /;
Main( @ARGV );
exit( 0 );
sub Main {
return Usage() unless @_ ;
for my $file ( @_) {
print "Converting $file \n";
ConvertFile( $file );
}
}
sub ConvertFile {
my $infilename = shift;
my ($outfh, $outfilename) = tempfile();
open my($infh), '<', $infilename; # autodie dies on error
while( my $line = <$infh> ){
chomp $line;
$line =~ s/sample\_\d\_x?/ID\t/i;
print $outfh $line, "\n";
}
close $infh;
close $outfh;
move( $outfilename, $infilename ); # autodie dies on error
}
sub Usage {
print <<"__USAGE__";
$0
$0 modify/this/file
perl ${\__FILE__}
perl ${\__FILE__} modify/this/file
__USAGE__
} ## end sub Usage
__END__
See use, autodie, open, File::Copy, File::Temp, strict, warnings, perlintro, perlretut, perlrequick, YAPE::Regex::Explain, Beginning Perl (free) Chapter 6: Files and Data, Modern Perl: Chapter 9: Managing Real Programs > Files |