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

Re: If statement not working

by GrandFather (Saint)
on Aug 25, 2012 at 01:05 UTC ( [id://989670]=note: print w/replies, xml ) Need Help??


in reply to If statement not working

I'd use a hash to manage the colour/replacement pairs. Consider:

use strict; use warnings; my %colours = ( 'baby blue' => 'BB', 'baby pink' => 'BP', 'dark blue' => 'DB', 'dark purple' => 'DP', 'hot pink' => 'HP', 'light purple' => 'LP', 'pink' => 'PK', 'pinkish' => 'PI', ); my $colourMatch = join '|', sort {length $b <=> length $a || $a cmp $b} keys %colours; for my $colour ('baby blue', 'baby pink', 'baby green', 'pink', 'pinki +sh') { if ($colour =~ /($colourMatch)/) { print "Matched $colour: $colours{$1}\n"; } else { print "Unmatched: $colour\n"; } }

Prints:

Matched baby blue: BB Matched baby pink: BP Unmatched: baby green Matched pink: PK Matched pinkish: PI

Note that the sort is there so that pinkish is matched correctly rather then being matched by 'pink'. Depending on the order of your tests and the strings being tested you current code would suffer from the same problem.

True laziness is hard work

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-25 05:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found