Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation


by Baz (Friar)
on Sep 07, 2002 at 22:45 UTC ( #195915=perlquestion: print w/replies, xml ) Need Help??

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

I have a do-while, and I'd like to have a character variable which is incremented for each iteration of the loop. So first time its a, then b up to z. Whats the best way to do this?

Replies are listed 'Best First'.
Re: Character++
by dreadpiratepeter (Priest) on Sep 07, 2002 at 22:48 UTC
    Perl once again makes easy things easy. Simply use the automagical increment operator just as you would for a numerical counter. i.e.:
    my $ctr='a'; print $ctr++ . "\n" foreach (1..26);
    You can also do things like 'aa'..'zz'.

    "Pain heals. Chicks dig scars. Glory lasts forever."
      But to decrement:
      my $ctr = 'a'; $ctr = chr( ord($ctr) - 1);
      Not sure why they decided not to implement -- on chars. (Thanks to Dog and Pony and Zaxo for pointing me to page 354 in Programming Perl for that.)
        Not sure why they decided not to implement -- on chars
        Not every computational process is reversable, nor should it be. "clintp"-- probably would go to "clinto" you'd think.

        "aa"-- might even logically go to "z", but then where should "a"-- go? "-a"? undef? ""? "`"? (how about on ebcdic systems?) Throw a warning (eeek! no warnings 'autodecrementascii'), throw an error (not remotely perlish!)?

        Sometimes language features are nice, you acknowledge them, maybe use them, move on, and not think too hard about making them fit into every conceivable programmatic niche you can think of. Perl's gotten in trouble for this kind of nonsense before (pseudohashes, v-strings). Enjoy magical autoincrement. And remember putting magic under a microscope takes all of the joy out of it.

        In which case, for small ranges, reverse 'a' .. 'z', might be a better choice.

        perl -pew "s/\b;([mnst])/'$1/g"

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (1)
As of 2023-06-01 19:27 GMT
Find Nodes?
    Voting Booth?

    No recent polls found