Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

transliterate a sub-string

by onlyIDleft (Scribe)
on Jan 15, 2013 at 23:00 UTC ( [id://1013467]=perlquestion: print w/replies, xml ) Need Help??

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

Dear Monks,

I wish to transliterate only a sub-string in a text rather than all of the text. I know how to use tr and substr, but my solution combining these two is clumsy at best. Is there one function or operator that can achive transliteration, but specifically on just a range within a string, rather than on the whole string?

Replies are listed 'Best First'.
Re: transliterate a sub-string
by johngg (Canon) on Jan 15, 2013 at 23:07 UTC

    As you don't show how you have combined the two it is difficult to judge. This seems fairly straightforward and not too clumsy. I'm not sure how that might be condensed further.

    $ perl -E ' > $str = q{ABCDEFGHIJK}; > substr( $str, 3, 3 ) =~ tr{A-Z}{a-z}; > say $str;' ABCdefGHIJK

    I hope this is helpful.

    Cheers,

    JohnGG

      This is neat, but was certainly not obvious. Maybe it is worth reminding that indeed substr can be used as a lvalue, as explicitely said in its perldoc:

      You can use the substr() function as an lvalue, in which case EXPR must itself be an lvalue. If you assign something shorter than LENGTH, the string will shrink, and if you assign something longer than LENGTH, the string will grow to accommodate it. To keep the string the same length, you may need to pad or chop your value using "sprintf".

        as explicitely said in its perldoc:

        Said and shown :)

        my $name = 'fred'; substr($name, 4) = 'dy'; # $name is now 'freddy' my $null = substr $name, 6, 2; # returns "" (no warning) my $oops = substr $name, 7; # returns undef, with warning substr($name, 7) = 'gap'; # raises an exception

        Note that the lvalue returned by the three-argument version of substr() acts as a 'magic bullet'; each time it is assigned to, it remembers which part of the original string is being modified; for example:

        $x = '1234'; for (substr($x,1,2)) { $_ = 'a'; print $x,"\n"; # prints 1a4 $_ = 'xyz'; print $x,"\n"; # prints 1xyz4 $x = '56789'; $_ = 'pq'; print $x,"\n"; # prints 5pq9 }

        Wow, I can copy/paste :)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-18 01:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found