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

I am creating a hash like

my %hash= ( "rabbit" = "pap", "triangle" = "tri", and so on.. +);

I want to match key in input and replace it with its value. How can i do it? Thank you

Replies are listed 'Best First'.
Re: Pattern matching with hash keys
by eyepopslikeamosquito (Archbishop) on Oct 04, 2010 at 06:15 UTC

    Your syntax is invalid. Instead of = between the key and the value, you need the "fat comma" => as shown below. Does this do what you want?

    use strict; use warnings; my %hash = ( "rabbit" => "pap", "triangle" => "tri" ); my $key = "rabbit"; print $hash{$key}; # prints "pap"

      All rite i will change the syntax as it is wrong, However, What i want is to match key value with input string.

      Like If $str contains "Rabbit" or "rabbit" i want it to be replaced with "pap". I am tring to use hash as there are n number values that i want to match and replace

        If $str contains "Rabbit" or "rabbit" i want it to be replaced with "pap".
        Hashes, by default, are case sensitive. However, if you take care to create the hash with all lower case keys, you could then simply lower case each input string, for example:
        use strict; use warnings; my %hash = ( "rabbit" => "pap", "triangle" => "tri" ); my $key = "rabbit"; print $hash{ lc($key) }, "\n"; # prints "pap" $key = "Rabbit"; print $hash{ lc($key) }, "\n"; # also prints "pap"

        You can do that with regex with 'i' option modifier which stands for ignore case. Refer perlre. For example,

        $str =~ /rabbit/i
        But TIMTOWTDI, you can do that with functions also.

        Prasad

Re: Pattern matching with hash keys
by AnomalousMonk (Archbishop) on Oct 04, 2010 at 08:36 UTC

    Also this:

    >perl -wMstrict -le "my %replace = (rabbit => 'pap', triangle => 'tri', andso => 'on'); ; my $search = join '|', keys %replace; $search = qr{ $search }xmsi; ; while (<>) { last if m{\A \s* \z}xms; s{ \b ($search) \b }{ $replace{lc $1} }xmsge; print qq{'$_'}; } " Andso rabbit Xrabbit rabbitX XrabbitX RaBbIt 'on pap Xrabbit rabbitX XrabbitX pap ' Triangle Triangles 'tri Triangles '

    See also perlretut, perlreref, perlrequick.

Re: Pattern matching with hash keys
by prasadbabu (Prior) on Oct 04, 2010 at 06:18 UTC

    Hi tej,
    Replace "=" with "=>" or ",". For example:

    %hash = ("rabbit" => "test"); $string = "rabbit"; if ($string =~ /rabbit/){ $string = $hash{"rabbit"}; }

    Prasad