David Chan writes:
> Hmmm.  When doing multiple substitutions, it would be nice to avoid a
> hard-to-read nested function call which reads backwards, a la python:
> 
>   return re.sub('>','&gt;',re.sub('<','&lt;',re.sub('&','&amp;',text)))
> 
> ... but to also avoid multiple statements like this:
> 
>   my $tmp = $_;
>   $tmp =~ s/&/&amp;/g;
>   $tmp =~ s/</&lt;/g;
>   $tmp =~ s/>/&gt;/g;
>   return $tmp;

Well, assuming we have:

    method Str::s(Pair $sub) returns Str {...}

We can write:

    .s(/&/  => '&amp;')
    .s(/\</ => '&lt;')
    .s(/\>/ => '&gt;');

But that's not great (not bad, though).  But it's been recognized for
awhile that substitutions like these need behavior more like a
generalized "tr":

    .s(/&/  => '&amp;',
       /\</ => '&lt;',
       /\>/ => '&gt;');

Both of these, of course, poses a problem with the scope of $1 et al.,
which can be fixed by:

    .s(/ \> (\w+) \< / => { do_stuff(.{1}) })

But that's starting to look pretty convoluted, and pretty unperlish.



> But maybe it'd be useful to have more visual weight than 's' carries:
> 
>   return $_.s:e/&/&amp;/.s:e/</&lt;/.s:e/>/&gt;/;   # line noise?

Only if you write it that way.  Most of perl can be line noise if you
want it to.

    return .s:e/  & /&amp;/
           .s:e/ \< /&lt;/
           .s:e/ \> /&gt;/;

Not so different from my first example above, except slightly more
traditional.  The fact that it's a method call means we don't have to
use ~~, which is a big win :-)

This still doesn't quite seem right...

>   return $_.sub:e("&","&amp;").sub:e("<","&lt;").sub:e(">,&gt;") # awkward
>   return $_.sub:e(&)(&amp;).sub:e(<)(&lt;).sub:e(>)(&gt;) # hmmm
> 
> But I forget whether we're allowed space by the dot, which could help.
> 
>   return $_ . s:e/&/&amp;/ . s:e/</&lt;/ . s:e/>/&gt;/;   # readabler

Whitespace is allowed before the dot, but not after it.  At least that's
the case when you're subscripting; method calls might be a different
story.

Luke

> -- 
> $_=".--- ..- ... -  .- -. --- - .... . .-.  .--. . .-. .-..  .... .- -.-.".
> " -.- . .-.\n";s!([.-]+) ?!$_=$1;y/-./10/;$_=chr(-1+ord pack"B*","01".0 x(5
> -length)."1$_");y/DWYKAQMOCVLSFENU\\IGBHPJXZ[~nfb`_ow{}/a-z0-9/;$_!ge;print
> 

Reply via email to