map_file#
Open a file by name and attach it to a scalar as a memory map.
Synopsis#
map_file my $map, $filename; # read-only
map_file my $map, $filename, '+<'; # read/write
map_file my $map, $filename, '<', $offset, $length;
Arguments#
$lvalue— scalar to receive the mapping. Any previous value is discarded. The variable must not already be mapped.$filename— path to the file. The file is opened with a:rawlayer added automatically, so encoding and newline translation never interfere with the mapping.$mode— defaults to'<'. Accepted values are'<','+<','>', and'+>', with the same meaning asopen.$offset— byte position at which the mapping starts. Defaults to0.$length— length of the mapping in bytes. Defaults to-s($filename) - $offset, i.e. the rest of the file.
Examples#
Read an entire file into a scalar without loading it eagerly:
map_file my $text, 'big.log';
print "lines: ", scalar(() = $text =~ /\n/g), "\n";
Patch bytes inside a binary file:
map_file my $map, 'image.bin', '+<';
substr $map, 0, 4, "MZ\0\0";
Map a window into a large file:
map_file my $chunk, 'archive.tar', '<', 1024 * 1024, 4096;
Edge cases#
Opening a zero-length file succeeds but produces a mapping that cannot be written to; writes are silently truncated to the empty string.
$offsetdoes not need to be page-aligned; the module adjusts internally.A filehandle with a non-binary PerlIO layer is rejected.
Going out of scope unmaps the variable; an explicit
unmapis rarely needed.
Differences from upstream#
Fully compatible with upstream File::Map 0.71.
See also#
map_handle— same operation starting from an open filehandle.map_anonymous— allocate a scratch region with no backing file.sys_map— drop down to rawmmap(2)flags.unmap— release a mapping explicitly before scope exit.sync— flush writes to disk without waiting for scope exit.