Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re^2: substr question

by johngg (Abbot)
on Aug 04, 2013 at 13:05 UTC ( #1047793=note: print w/replies, xml ) Need Help??

in reply to Re: substr question
in thread substr question

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.



Replies are listed 'Best First'.
Re^3: substr question
by lightoverhead (Pilgrim) on Aug 05, 2013 at 23:07 UTC

    Thank you JohnGG !

    Maybe that's the internal implement of substr's behavior when it is used in a for loop. Thank you for your detailed example. I do learn a lot from it.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1047793]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2018-06-23 03:13 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.