Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Python dict to perl hash

by Anonymous Monk
on Mar 30, 2015 at 11:41 UTC ( [id://1121804]=note: print w/replies, xml ) Need Help??


in reply to Python dict to perl hash

Given only your example, that looks fine. But if the input dict gets more complicated, the method may break, so it's not a good general-purpose solution. If this is a one-time thing, why not replace my $x = ... with the Dumper output, so you've got the hash written directly in Perl? Or, are you looking for a general solution?

Replies are listed 'Best First'.
Re^2: Python dict to perl hash
by frozenwithjoy (Priest) on Mar 30, 2015 at 15:24 UTC

    I think replacing this:

    $x =~ s/['\s+]//g; my %hash = split /[:,]/, $x;

    with this:

    $x =~ s/'\s*:\s*'/' => '/g; my %hash = %{ eval "{$x}" };

    would make it less breakable (but still breakable if and keys or values contained something like "' : '").

Re^2: Python dict to perl hash
by garg10may (Initiate) on Mar 30, 2015 at 12:01 UTC
    But I copied that dict from somewhere and need to convert it to hash to work upon it. I cannot have dumper output without the input. So yes you can say in general.

      If you need THAT hash, here it is

      my %hash = map { chr(65+$_)=>chr(65+($_+13)%26), chr(97+$_)=>chr(97+($_+13)%26)} 0..25;
      But I copied that dict from somewhere ...

      It's still unclear to me whether you're talking about only this one dict? Or whether you have a bunch of different dicts that you need to translate to Perl?

      The code you showed produces an output: a hash(ref) in Perl's own syntax. Copy that output back into your Perl script, replacing your current hash definition, and you'll have a hash defined in pure Perl.

      sub rot13 { my %hash = ( a=>"n", b=>"o", c=>"p", ... ); ... }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-03-28 20:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found