A few minutes ago, a node was posted as to why auto-decrement (--) wasn't magical. Since auto-increment is, this seems natural. It inspired me to throw together just such a function.

This is brute force, but it works. It's surprisingly difficult for something that looks so simple! So I'd love to see how this can be improved on—what language features could be brought to bear?

Perhaps reverse the string, then do a s///ge with inline code for a done flag as a zero-width lookahead, and the predchar feature in the replacement? Yaphy?

—John

use strict; use warnings; sub predchar # modify argument in place. # return true if no carry (done). { my $ord= ord($_[0]); my $nocarry; # define the ranges available my @ranges= ( [ord('0'),ord('9')], [ord('a'),ord('z')], [ord('A'),ord +('Z')] ); foreach my $range (@ranges) { my ($first,$last)= @$range; next unless $ord >= $first && $ord <= $last; # my range? if ($ord == $first) { $ord= $last } else { --$ord; $nocarry= 1; } } $_[0]= chr($ord); return $nocarry; } sub magic_decrement($) { my @chars= split ('', shift); for (my $loop= $#chars; $loop>=0; --$loop) { last if predchar ($chars[$loop]); } return join ('',@chars); } sub test { my $s= shift || $_; my $result= magic_decrement($s); print qq{--"$s" gives "$result"\n}; } while (<DATA>) { chomp; test; } __DATA__ 123 abc testbaA ignore punct.

In reply to Magical Auto-Decrement by John M. Dlugosz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.