Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a script that works where I am replacing words in a file but was wondering if there is a way to do this? Right now I use "$line =~ s/....." four times to substitute data. Anyway to make it look better???
open(DATA, ">$_") or die "File not open: $!"; foreach $line (@data) { $line =~ s/AAA/EEE/gi; $line =~ s/CCC/NEWWORD/gi; $line =~ s/UUU/NEW/gi; $line =~ s/ERD/IPK/gi; print DATA $line; } close(DATA);

Replies are listed 'Best First'.
•Re: Substitute data issue
by merlyn (Sage) on Jun 27, 2003 at 13:31 UTC
Re: Substitute data issue
by broquaint (Abbot) on Jun 27, 2003 at 13:36 UTC
    You could use a hash e.g
    my %repmap = qw( AAA EEE CCC NEWWORD UUU NEW ERD IPK ); my $find = join '|', keys %repmap; s/($find)/$repmap{$1}/ig, print DATA $_ for @data;

    HTH

    _________
    broquaint

Re: Substitute data issue
by gjb (Vicar) on Jun 27, 2003 at 13:36 UTC

    You could make it look better (but probably less efficient, although you should benchmark this) by using a hash for the substitution.

    my %subst = ( 'AAA' => 'EEE', 'CCC' => 'NEWWORD', 'UUU' => 'NEW', 'ERD' => 'IPK' ); my $pattern = join('|', keys %subst);
    and replacing the body of the foreach by:
    $line =~ s/($pattern)/$subst{$1}/gi;
    Note: this is untested.

    Hope this helps, -gjb-

    Update: thanks to broquaint for pointing out that I should drop the /e as regex modifier. Silly, I wasn't thinking.

Re: Substitute data issue
by Zaxo (Archbishop) on Jun 27, 2003 at 13:41 UTC

    You should pick another filehandle name. DATA is reserved for perl, providing data from the script file itself.

    After Compline,
    Zaxo

      Thanks for all the information from all of you!
Re: Substitute data issue
by diotalevi (Canon) on Jun 27, 2003 at 13:37 UTC

    Ahtt's already a good representation.You could abstract this a little but not much.