Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Array Element Substitution

by Marshall (Abbot)
on Aug 24, 2012 at 10:17 UTC ( #989480=note: print w/replies, xml ) Need Help??


in reply to Array Element Substitution

I guess that this would also be a solution.
Adapt to your application..
#!/usr/bin/perl -w use strict; my $heredoc = <<END; This is a whole bunch of stuff with Jupiter and Mars and Earth and Venus and Saturn. Also could be Earth and Earth and something else like Neptune. END my $xlatedoc = <<END; Jupiter host1 Mars host2 Earth host3 END my %xlate; open (XLATE, '<', \$xlatedoc) or die "xlatedoc failed: $!\n"; while (<XLATE>) { my ($planet, $host) = split; #no chomp() needed $xlate{$planet}=$host; } close (XLATE); my @planets = keys %xlate; my $all_planets = join ('|',@planets); open (IN, '<', \$heredoc) or die "heredoc failed: $!\n"; while (<IN>) { s/($all_planets)/$xlate{$1}/g; # $all_planets is an OR expression # $1 winds up being which one of the OR'ed terms matched # that gets translated to the new term print; } __END__ This is a whole bunch of stuff with host1 and host2 and host3 and Venus and Saturn. Also could be host3 and host3 and something else like Neptune.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://989480]
help
Chatterbox?
[Cosmic37]: now I have tried another blunder - can anyone explain why I am such a dunderhead?
[Cosmic37]: if ( $line =~ /$mydt/ ) { print $line; }
[Cosmic37]: I try to match successive date times stored in variable $mydt
[Cosmic37]: I guess it is searching for the string "$mydt"
[Corion]: Indeed cool, erix ;)
[Cosmic37]: rather than the value of $mydt which is a date time strong such as 2016-01-01 12:30:56
[Corion]: Cosmic37: No, but maybe $mydt doesn't contain what you think it does, or it contains characters that are special in a regular expression? Try if( $line =~ /\Q$mydt\E/) { ... for a literal match
[Cosmic37]: I mean string grrr
[Corion]: Maybe add an else branch in which you print what the values of $line and $mydt are?
[Cosmic37]: ah thank you I will try

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (8)
As of 2017-06-29 17:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many monitors do you use while coding?















    Results (673 votes). Check out past polls.