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

Finally, days later, most of the script is finally setup. It isn't exactly how I want it, it still has problems if the right side is null but I'll be using === to represent "nothing" and fix that later.

This is the main question I was wondering about when this project started.. I'm trying to do a s/// with two arrays, substitute @first_half with @second_half. The arrays are setup in such a way where $first_half[0] is to be replaced with $second_half[0] and so on-- so the array indexes are aligned perfectly.

open(FILE, "file.txt") or die "Oops:$!"; my $contents = <FILE>; while (<FILE>) { do every possible s/// with the two arrays here }
Any help would be very appreciated and out of curiousity, have any of you done something like this before or is this a rather silly way to do it?

Thank you wise monks.



"Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

sulfericacid

Replies are listed 'Best First'.
Re: s/// with 2 arrays
by Paladin (Vicar) on Jun 07, 2004 at 16:08 UTC
    Does the order of the substitution matter? If not, try:
    my %subst; @subst{@first_half} = @second_half; s/\Q$_\E/$subst{$_}/ for keys %subst;
    Or if order does matter:
    for (my $i = 0; $i < @first_half; $i++) { s/\Q$first_half[$i]\E/$second_half[$i]/; }
    You may want to remove the \Q\E from each s/// if the REs aren't just strings, but have meta-chars in them, and you'll have to bind the s/// to whatever variable has the line in it too, of course.
Re: s/// with 2 arrays
by davido (Cardinal) on Jun 07, 2004 at 16:09 UTC
    while ( my $line = <FILE> ) { foreach ( 0 .. $#first_half ) { $line =~ s/$first_half[$_]/$second_half[$_]/; } }
    Might be a better design philosophy to set up the LHS as keys and RHS as values to a hash, and just iterate over the keys. But that's a matter of choice; either way works. Also, remember to use \Q \E if necessary, or pass RE objects using qr//.


    Dave