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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: lhs substr(): refs vs. scalars
by renodino (Curate) on Oct 08, 2005 at 18:24 UTC | |
by BrowserUk (Patriarch) on Oct 08, 2005 at 18:57 UTC | |
by renodino (Curate) on Oct 08, 2005 at 19:41 UTC | |
by ysth (Canon) on Oct 09, 2005 at 03:45 UTC | |
by BrowserUk (Patriarch) on Oct 09, 2005 at 04:33 UTC | |
by ysth (Canon) on Oct 09, 2005 at 04:40 UTC |