Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

How to replace strings in a file from a list?

by zBernie (Novice)
on Oct 03, 2012 at 00:53 UTC ( #996943=perlquestion: print w/ replies, xml ) Need Help??
zBernie has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying replace names in a file, with names from a list included in __DATA__ in the script
below. Now assume I have a text file which contains hundreds of
different names, and I want to replace certain ones with a mapping of say:
JOE -> JOHN
FRED -> FREDERICK
SAM -> SAMANTHA

Do I need to create a hash with the 6 names above before I can replace instances of
JOE, FRED, and SAM, in a text file?

#!/usr/bin/perl -w use strict; if ($#ARGV < 0) { print "\nUsage: $0 <File>\n\n"; exit 0; } my $userlist = qq{$ARGV[0]}; open(FILE, qq{$userlist}) or die("$!: $userlist"); my @users = <FILE>; close(FILE); while ( <DATA> ) { print $_; } __DATA__ JOE FRED SAM

Comment on How to replace strings in a file from a list?
Download Code
Re: How to replace strings in a file from a list?
by toolic (Chancellor) on Oct 03, 2012 at 02:21 UTC
    Do I need to create a hash with the 6 names above before I can replace instances of JOE, FRED, and SAM, in a text file?
    Yes, that is one way to do it. Give it a try.

    Also note that you can simplifiy your code a little by eliminating qq around your variables:

    my $userlist = $ARGV[0];
Re: How to replace strings in a file from a list?
by Kenosis (Priest) on Oct 03, 2012 at 03:49 UTC

    Here's another option:

    use strict; use warnings; use File::Slurp qw/ read_file write_file /; $ARGV[0] or die "\nUsage: $0 <File>\n\n"; my $userlistContents = read_file $ARGV[0]; for ( grep /\S/, <DATA> ) { my ( $before, $after ) = split; $userlistContents =~ s/\b$before\b/$after/g; } write_file "changed_$ARGV[0]", $userlistContents; __DATA__ JOE JOHN FRED FREDERICK SAM SAMANTHA

    Using File::Slurp is a nice way to get the file's contents into a scalar upon which global substitutions can be performed. The before and after names in the __DATA__ area are tab separated. Note that the changed file contents are written to the file named "changed_$ARGV[0]".

    Hope this helps!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://996943]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (11)
As of 2014-12-22 20:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (128 votes), past polls