Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Replacing string with number

by nejcPirc (Acolyte)
on Sep 30, 2004 at 11:50 UTC ( [id://395311]=perlquestion: print w/replies, xml ) Need Help??

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

Hello.
I would like to replace my scalar value(string) with a key's value(number), which is included in hash.
So if i have a month called January it should be changed to "01";
$month="January"; %months=('January' =>01, 'February' =>02, 'March' =>03, 'April' =>04, 'May' =>05, 'June' =>06, 'July' =>07, 'August' =>08, 'September'=>09, 'October' =>10, 'November' =>11, 'December' =>12 ); # if($month ?in? %months) # { $month=%months{$month}; } print "$month\n"; #output-> "01"
Thanx.

Replies are listed 'Best First'.
Re: Replacing string with number
by Arunbear (Prior) on Sep 30, 2004 at 11:53 UTC
    Use exists : if(exists $months{$month}) { $month = $months{$month} }
      Thanks a lot:)
Re: Replacing string with number
by tachyon (Chancellor) on Sep 30, 2004 at 11:54 UTC
    # simple literal key only $month = $months{$month} if exists $month{$month}; # more flexible any instance my $re = join '|', map{quotemeta} keys %months; $month =~ s/($re)/$months{$1}/g;

    Note you need to quote strings on the RHS of => otherwise Perl will see 08 and complain about your illegal octal.

    cheers

    tachyon

Re: Replacing string with number
by ikegami (Patriarch) on Sep 30, 2004 at 14:42 UTC

    Another way, for fun:
    $month=$months{$month}||$month;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2024-04-19 14:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found