http://qs321.pair.com?node_id=498434


in reply to lhs substr(): refs vs. scalars

You know you can use substr as an lvalue or with a fourth parameter to avoid duplicating your big scalars.

If you need to use unpack to decode small chunks of the buffer, or pack to overwrite small chunks, use them in conjunction with substr to avoid copying:

my @decoded = unpack '...', substr $bigscalar, $offset, $size; substr $bigscalar, $offset, $size, pack '...', @newValues; # or substr( $bigscalar, $offset, $size ) = pack '...', @newValues;

But be very sure that the size specified in substr, and the size of the result from pack match exactly, otherwise you will be expanding or shrinking your big scalar by the difference which will lead to nasty surprises. It may be better to use an intermediary variable here:

my $replacement = pack '...', @newValues; substr( $bigScalar, $offset, length $replacement ) = $replacement;

It is also possible (from 5.8.5 onwards) to set up an array of lvalue references to chunks of your scalar and then manipulate the individual chunks through indirection:

## Create a scalar perl> $bigScalar = 'the quick brown fox jumps over the laxy dog';; ## Create an array of lvalue refs to the indivdual words using \substr +... perl> @lvrefs = map{ \substr $bigScalar, $_->[0], $_->[1] } [0,3], [4,5], [10,5], [16,3], [20,5], [26,4], [31,3], [35,4], [40,3] +;; ## Indirecting through the elements of the array gives you the words perl> print $$_ for @lvrefs;; the quick brown fox jumps over the laxy dog ## And assign through the elements allows you to replace them, in-plac +e, individually perl> ${ $lvrefs[7] } = 'lazy';; ## The ${ ... } is necessary. ## The typo is now corrected. perl> print $bigScalar;; the quick brown fox jumps over the lazy dog

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.