Mmap is a Perl module that uses mmap to map in a file as a Perl variable.
new Mmap $str, 8192, 'structtest2.pl' or die $!;
new Mmap $var, 8192 or die $!;
mmap($foo, 0, PROT_READ, MAP_SHARED, FILEHANDLE) or die "mmap: $!";
@tags = $foo =~ //g;
munmap($foo) or die "munmap: $!";
mmap($bar, 8192, PROT_READ|PROT_WRITE, MAP_SHARED, FILEHANDLE);
substr($bar, 1024, 11) = "Hello world";
mmap($baz, 8192, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, STDOUT);
$addr = mmap($baz, 8192, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, STDOUT);
Sys::Mmap::hardwire($qux, $addr, 8192);
The Mmap module uses the POSIX mmap call to map in a file as a Perl variable. Memory access by mmap may be shared between threads or forked processes, and may be a disc file that has been mapped into memory. Sys::Mmap depends on your operating system supporting UNIX or POSIX.1b mmap, of course.
Note that PerlIO now defines a :mmap tag and presents mmap'd files as regular files, if that is your cup of joe.
Several processes may share one copy of the file or string, saving memory, and concurrently making changes to portions of the file or string. When not used with a file, it is an alternative to SysV shared memory. Unlike SysV shared memory, there are no arbitrary size limits on the shared memory area, and sparce memory usage is handled optimally on most modern UNIX implementations.
Using the new() method provides a tie()'d interface to mmap() that allows you to use the variable as a normal variable. If a filename is provided, the file is opened and mapped in. If the file is smaller than the length provided, the file is grown to that length. If no filename is provided, anonymous shared inheritable memory is used. Assigning to the variable will replace a section in the file corresponding to the length of the variable, leaving the remainder of the file intact and unmodified. Using substr() allows you to access the file at an offset, and does not place any requirements on the length argument to substr() or the length of the variable being inserted, provided it does not exceed the length of the memory region. This protects you from the pathological cases involved in using mmap() directly, documented below.
When calling mmap() or hardwire() directly, you need to be careful how you use the variable. Some programming constructs may create copies of a string which, while unimportant for smallish strings, are far less welcome if you're mapping in a file which is a few gigabytes big. If you use PROT_WRITE and attempt to write to the file via the variable you need to be even more careful. One of the few ways in which you can safely write to the string in-place is by using substr() as an lvalue and ensuring that the part of the string that you replace is exactly the same length. Other functions will allocate other storage for the variable, and it will no longer overlay the mapped in file.