Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: modifying a file with regex!

by Anonymous Monk
on Mar 16, 2012 at 22:11 UTC ( [id://960077]=note: print w/replies, xml ) Need Help??


in reply to modifying a file with regex!

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://960077]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-04-25 12:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found