The most efficient way I know of is to use a ramfile and seek (Note: the space allocated is uninitialised).
The nice thing about this is that if you need to extend it, you can, and any existing contents will be preserved even if Perl has to re-allocate a larger chunk of ram.
#! perl -slw use strict; my $bigstring; open my $temp, '>', \$bigstring or die $!; print $temp 'My oh so unique signature'; seek $temp, 2**19, 0; print $temp chr(0); close $temp; print length $bigstring; open $temp, '+<', \$bigstring or die $!; seek $temp, 2**20, 0; print $temp chr(0); close $temp; print length $bigstring; print substr $bigstring, 0, 25; __END__ c:\test>junk6 524290 1048578 My oh so unique signature
But then I've never found a way to truncate that (so that I can append to it), without risking having the space returned to the pool. So, I've used substr as an lvalue with a pointer to manage the space myself:
my $p = 0; substr( $bigstring, $p, 4 ) = pack 'J', .. $p += 4;
Two caveats are: 1) truncate doesn't seem to work on ramfiles; 2) if you over allocate, the unused space remains as a part of the string until you do something about it. Eg.
substr( $bigstring, $p+1 ) = '';
In reply to Re: Pre-grow a string
by BrowserUk
in thread Pre-grow a string
by diotalevi
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |