I don't think it is a case of substr "remembering" the length and offset. I think it is more to do with the fact that $_ inside the for loop is an alias (effectively a reference) to each item in the list in turn; in this case just one item, the sub-string. Using a reference to the sub-string, the following code demonstrates that because it is being assigned to, the referenced sub-string will be of the length of the last assignment regardless of the fact that it was originally only two characters long. Remaking the reference each time keeps the length at two as you would expect.
use strict;
use warnings;
use feature qw{ say };
my $str = q{1234};
my $ref = \ substr $str, 1, 2;
show();
noRefReset( $_ ) for qw{ a xyz };
$str = q{56789};
show();
noRefReset( $_ ) for qw{ pq ghijkl st };
say q{-} x 18;
$str = q{1234};
$ref = \ substr $str, 1, 2;
show();
refReset( $_ ) for qw{ a xyz };
$str = q{56789};
show();
refReset( $_ ) for qw{ pq ghijkl st };
sub noRefReset
{
${ $ref } = shift;
show();
}
sub refReset
{
${ $ref } = shift;
$ref = \ substr $str, 1, 2;
show();
}
sub show
{
printf qq{%-9s - %s\n}, $str, ${ $ref };
}
The output.
1234 - 23
1a4 - a
1xyz4 - xyz
56789 - 678
5pq9 - pq
5ghijkl9 - ghijkl
5st9 - st
------------------
1234 - 23
1a4 - a4
1xyz - xy
56789 - 67
5pq89 - pq
5ghijkl89 - gh
5stijkl89 - st
I hope this is of interest.
-
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.