sobering observation, python vs. perl

BartC bc at freeuk.com
Thu Mar 17 13:53:41 EDT 2016


On 17/03/2016 17:25, Charles T. Smith wrote:
> On Thu, 17 Mar 2016 19:08:58 +0200, Marko Rauhamaa wrote:

>>     my $str = "I have a dream";
>>     my $find = "have";
>>     my $replace = "had";
>>     $find = quotemeta $find; # escape regex metachars if present
>>     $str =~ s/$find/$replace/g;
>>     print $str;
>>
>> with Python:
>>
>>     print("I have a dream".replace("have", "had"))

> Uh... that perl is way over my head.  I admit though, that perl's
> powerful substitute command is also clumsy.  The best I can do
> right now is:
>
> $v =  "I have a dream\n";
> $v =~ s/have/had/;
> print $v

I was going to suggest just using a function. But never having coded in 
Perl before, I wasn't expecting something this ugly:

sub replacewith{
    $s = $_[0];
    $t = $_[1];
    $u = $_[2];
    $s =~ s/$t/$u/;
    return $s;
}

Although once done, the original task now looks a proper language:

print (replacewith("I have a dream","have","had"));

-- 
Bartc



More information about the Python-list mailing list