Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Not sure what the use case is. Here's my assumption: you're going to do a one-time conversion from Perl to Python.</p> <p>Perl has this</p> <pre><code>%config = ( 'color' =&gt; 'red', 'numbers' =&gt; [5, 8], qr/^spam/ =&gt; 'eggs' ); </code></pre> <p>In Python, it would be</p> <pre><code>config = { 'color' : 'red', 'numbers' : [5, 8], re.compile( "^spam" ) : 'eggs' } </code></pre> <p>So, I'm guessing it's a bunch of RE's to replace </p> <ul> <li><code>%variable = (</code> with <code>variable = {</code></li> <li><code>);</code> with <code>}</code></li> <li><code>variable =&gt; value</code> with <code>variable : value</code></li> <li><code>qr/.../ =&gt;</code> with <code>re.compile( r"..." ) : value</code></li> </ul> <p>However, Python's built-in <code>dict</code> doesn't do anything unusual with a regex as a hash key. For that, you'd have to write your own subclass of <code>dict</code>, and override <code>__getitem__</code> to check REGEX keys separately.</p> <pre><code>class PerlLikeDict( dict ): pattern_type= type(re.compile("")) def __getitem__( self, key ): if key in self: return super( PerlLikeDict, self ).__getitem__( key ) for k in self: if type(k) == self.pattern_type: if k.match(key): return self[k] raise KeyError( "key %r not found" % ( key, ) ) </code></pre> <p>Here's the example of using a Perl-like dict.</p> <pre><code>&gt;&gt;&gt; pat= re.compile( "hi" ) &gt;&gt;&gt; a = { pat : 'eggs' } # native dict, no features. &gt;&gt;&gt; x=PerlLikeDict( a ) &gt;&gt;&gt; x['b']= 'c' &gt;&gt;&gt; x {&lt;_sre.SRE_Pattern object at 0x75250&gt;: 'eggs', 'b': 'c'} &gt;&gt;&gt; x['b'] 'c' &gt;&gt;&gt; x['ji'] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 10, in __getitem__ KeyError: "key 'ji' not found" &gt;&gt;&gt; x['hi'] 'eggs' </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload