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).
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.