in reply to find and replace project with values coming from a table

Put the first table into a hash, and loop over the second:
#!/usr/bin/perl use strict; use warnings; my %subs = map {@$_} [qw /jones B0/], [qw /smith B1/], [qw /adrew B2/], [qw /larry B3/]; my @data = ([qw /jones AAAAA BBBBB CCCCC/], [qw /aaaaa AAAAA larry CCCCC/], [qw /jones AAAAA BBBBB CCCCC/], [qw /DDDDD AAAAA BBBBB larry/], [qw /jones AAAAA adrew CCCCC/], [qw /jones smith BBBBB CCCCC/], ); foreach (@data) { foreach (@$_) { $_ = $subs {$_} || $_; } } $" = '", "'; print qq !["@$_"]\n! for @data; __END__ ["B0", "AAAAA", "BBBBB", "CCCCC"] ["aaaaa", "AAAAA", "B3", "CCCCC"] ["B0", "AAAAA", "BBBBB", "CCCCC"] ["DDDDD", "AAAAA", "BBBBB", "B3"] ["B0", "AAAAA", "B2", "CCCCC"] ["B0", "B1", "BBBBB", "CCCCC"]

Abigail

Replies are listed 'Best First'.
Re: Re: find and replace project with values coming from a table
by Aighearach (Initiate) on Jul 05, 2003 at 09:04 UTC
    Just one nit:
    If the replacement value is not true, it fails to replace.

    I recommend replacing

    $_ = $subs {$_} || $_;
    with
    $_ = exists $subs {$_} ? $subs {$_} : $_;
    so that a 0 could also be used as a replacement value.

    Although I must say, it does somewhat damage the visual aesthetics.
    --
    Snazzy tagline here

      I choose for the former because with the given data, the problem doesn't arise. If you want to be able to cope with possible false values (except for 0, the empty string, and undef would be false too) I would use:
      $_ = $subs {$_} if exists $subs {$_};

      The effect is the same of course, but it looks better IMO.

      Abigail

        Agreed, that does look a lot better! It's technically better too, as mine was foolishly replacing $_ with itself in the event of a failed match.
        --
        Snazzy tagline here