Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

tr/// on a list

by shoness (Friar)
on Sep 14, 2007 at 20:48 UTC ( #639077=perlquestion: print w/replies, xml ) Need Help??

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


I'd like to do an operation like tr/// on all elements of a list.

my @beatles = ('John', 'Paul', 'George', 'Ringo'); @beatles =~ tr/A-Z/a-z/; # <--- doesn't work !!!
I think I'm hung up because tr/// returns the number of matches.
I could use a foreach, but it seems not terribly perlish.

Thanks for your help!

Replies are listed 'Best First'.
Re: tr/// on a list
by grinder (Bishop) on Sep 14, 2007 at 21:38 UTC
    it seems not terribly perlish.

    Well actually, a foreach is actually quite perlish. To be terribly perlish, one would shorten it down to a for modifier that operates on $_ implicitly aliasing over each element

    for (@beatles) { tr /A-Z/a-z/ }

    written more concisely as

    tr /A-Z/a-z/ for @beatles;

    which is probably more elegant than a vulgar map.

    @beatles = map {lc} @beatles;

    update: gah! I do ramble on.

    • another intruder with the mooring in the heart of the Perl

      Because map operates on an alias of each element you don't need to assign the result of the map anywhere:

      map {$_= lc} @beatles;

      However map in a void context is frowned on so it would be more usual to use for/foreach as a statement modifier:

      $_ = lc for @beatles;

      DWIM is Perl's answer to Gödel
Re: tr/// on a list
by ikegami (Pope) on Sep 14, 2007 at 21:01 UTC
Re: tr/// on a list
by shoness (Friar) on Sep 14, 2007 at 23:04 UTC
    Thanks! I knew elegance was just a few deleted characters away.
    Those inside-out/backward for-loops and if-statements are terribly perlish, hence I rarely consider them when they're needed!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://639077]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2021-04-22 13:55 GMT
Find Nodes?
    Voting Booth?

    No recent polls found