Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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.

Cheers,

JohnGG


Comment on Re^2: substr question
Select or Download Code
Re^3: substr question
by lightoverhead (Monk) 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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1047793]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2014-11-29 04:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (203 votes), past polls