I'm not too familiar with overloading, so this is a "wonder if I can get that to work" snippet instead of a "I'd recommend doing it this way" suggestion.

Perhaps someone more familiar with overloading can point out the shortcomings of this quick hack. (other than not working for negative numbers, and the really poor algorithm of repeating $x++ 10 times for $x + 10)

#!/usr/bin/perl -wT use strict; package MagicalPlus; use overload '""' => sub { ${$_[0]} }, '+' => \&myadd, 'fallback' => 1; sub myadd { my $first = ${$_[0]}; my $second = $_[1]; $first++ while($second-->0); return addmagic($first); } sub addmagic { my $string = "".shift; my $self = \$string; bless($self, __PACKAGE__); } package main; my $x = MagicalPlus::addmagic "006"; # create our magic var for (1..10) { # watch it works its magic print "$x + $_ = "; $x = $x + $_; # magical? print "$x\n"; } =OUTPUT 006 + 1 = 007 007 + 2 = 009 009 + 3 = 012 012 + 4 = 016 016 + 5 = 021 021 + 6 = 027 027 + 7 = 034 034 + 8 = 042 042 + 9 = 051 051 + 10 = 061

-Blake


In reply to Re: Squeezing $a+1 to be magical like $a++ by blakem
in thread Squeezing $a+1 to be magical like $a++ by coolmichael

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.