Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Replace many array element with another corresponding array element in a file

by Kenosis (Priest)
on Oct 18, 2012 at 05:18 UTC ( #999669=note: print w/ replies, xml ) Need Help??


in reply to Replace many array element with another corresponding array element in a file

If your substitutions are working fine (no word-boundary issues), but just taking a long time (understandable, iterating through two arrays for substitutions on each file line), perhaps the following will be helpful:

my $TestText; { local $/; open( my $in, '<', "Test.txt" ) or die "cannot open Test.txt $!"; $TestText = <$in>; close $in; } $TestText =~ s/\Q$_\E/$hash{$_}/g for keys %hash; open( my $out, '>', "TestFinal.txt" ) or die "cannot create TestFinal +$!"; print $out $TestText; close $out;

This reads the entire file into a scalar, so substitutions are done on the entire file's contents. This also uses a hash's key/value pairs instead of different array element pairs, so you'll need to initialize the hash (%hash) accordingly for the three substitution pairs.

Hope this helps!

Edit: my $TestText ... to $TestText ... in the file slurp block and quotemeta \Q$_\E.


Comment on Re: Replace many array element with another corresponding array element in a file
Select or Download Code
Re^2: Replace many array element with another corresponding array element in a file
by faezshingeri (Initiate) on Oct 18, 2012 at 05:31 UTC
    I tried the following:
    my %hashvariable; @hashvariable{@variable} = @vardescription; my $TestText; { local $/; open( my $in, '<', "Test.txt" ) or die "cannot open Test.txt $!"; my $TestText = <$in>; close $in; } $TestText =~ s/$_/$hashvariable{$_}/g for keys %hashvariable; open( my $out, '>', "TestFinal.txt" ) or die "cannot create TestFinal +$!"; print $out $TestText; close $out;
    Output file TestFinal.txt is empty. Am I doing anything wrong?

      Oh, sheesh! No, I did something wrong.:

      my $TestText = <$in>;

      should be:

      $TestText = <$in>;

      Sorry about that. Will correct this in the original posting

      BTW - Excellent way to initialize the hash...

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (12)
As of 2014-09-19 11:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (135 votes), past polls