package Tie::Substr; use base 'Exporter'; @EXPORT = 'substr'; sub TIESCALAR { bless [ $_[1], 0 ], $_[0]; } sub FETCH { $_[0][1] = 1; @{ $_[0][0] } == 2 and return substr($_[0][0][0], $_[0][0][1]); @{ $_[0][0] } == 3 and return substr($_[0][0][0], $_[0][0][1], $_[0][0][2]); @{ $_[0][0] } == 4 and return substr($_[0][0][0], $_[0][0][1], $_[0][0][2], $_[0][0][3]); die; } sub STORE { $_[0][1] = 1; @{ $_[0][0] } == 2 and return substr($_[0][0][0], $_[0][0][1]) = $_[1]; @{ $_[0][0] } == 3 and return substr($_[0][0][0], $_[0][0][1], $_[0][0][2]) = $_[1]; eval 'substr($foo, 0, 0, 0) = ""'; die; } sub DESTROY { $_[0]->FETCH unless $_[0][1]; } sub substr : lvalue { tie my $foo, 'Tie::Substr', \@_; $foo }
Doesn't always give an error when used in void context (fails substr.t tests 120 and 121) and doesn't report the correct line numbers, because I was too lazy to wrap everything in evals. This substr of course doesn't support $[, of course, causing substr.t tests 8..14 to fail. But you shouldn't set $[ anyway. And the thing uses a tied variable, so don't expect lightening speeds.

Apart from those small and insignificant differences, it's compatible with normal substr, but with an lvalue per substr call :)

For testing, I used perl 5.8.0 with its own substr.t.

Juerd
- http://juerd.nl/
- spamcollector_perlmonks@juerd.nl (do not use).


In reply to Re: Re: Re: LVALUE refs by Juerd
in thread LVALUE refs by BrowserUk

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.