```{index} single: File::Map; Perl module ``` # File::Map ```{pperl-module-badges} File::Map ``` Memory-mapped scalars: make a file look like an ordinary string. `File::Map` attaches a file — or a fresh anonymous region of memory — to a Perl scalar. Reads and writes to the scalar go straight to the kernel's mapping: the file appears in your variable as a string, and changes propagate back without you ever calling `read` or `write`. A multi-gigabyte file costs almost nothing to open this way, because pages are faulted in lazily as you touch them. Once a scalar is mapped it behaves like a regular string for the operations that matter: `substr`, regex match and substitution, `index`, `length`, and slicing. Direct assignment (`$map = "..."`) is caught and fixed up so you never corrupt the mapping, though `substr` is the recommended way to write. The mapping is released automatically when the scalar goes out of scope; `unmap` is available for explicit control. ## Synopsis ```perl use File::Map qw(map_file map_anonymous unmap); map_file my $map, 'data.bin', '+<'; # read/write $map =~ s/foo/bar/g; # edits go to disk substr $map, 0, 4, "HEAD"; # in-place write map_anonymous my $buf, 4096, 'shared'; # scratch region unmap $map; # optional ``` ## Choosing a mapping function - `map_file` — give a filename and a mode, get a mapped scalar. The common case. - `map_handle` — same idea, but you already have an open filehandle. - `map_anonymous` — no file; a scratch region shared with forked children or private to the process. - `sys_map` — low-level wrapper around raw `mmap(2)` flags for when the convenience functions don't fit. ## Managing a live mapping - `sync` — flush pending writes back to disk. - `advise` — hint the kernel about access patterns (`"sequential"`, `"random"`, `"willneed"`, …). - `protect` — change read/write protection at runtime. - `remap` — resize an existing mapping (Linux only). - `unmap` — drop the mapping explicitly. ## Functions ### Mapping #### [`map_file`](Map/map_file) Open a file by name and attach it to a scalar as a memory map. #### [`map_handle`](Map/map_handle) Attach an already-open filehandle to a scalar as a memory map. #### [`map_anonymous`](Map/map_anonymous) Allocate a fresh memory region backed by no file and attach it to a scalar. #### [`sys_map`](Map/sys_map) Low-level mapping with raw `mmap(2)` protection and flag constants. #### [`remap`](Map/remap) Resize an existing mapping in place. ### Unmapping #### [`unmap`](Map/unmap) Release a mapping explicitly before the scalar goes out of scope. ### Synchronisation #### [`sync`](Map/sync) Flush pending writes from a mapped scalar back to disk. ### Advice #### [`advise`](Map/advise) Tell the kernel how the mapped region will be accessed. #### [`protect`](Map/protect) Change the read/write/execute protection of a mapped region. ```{toctree} :hidden: :maxdepth: 1 Map/map_file Map/map_handle Map/map_anonymous Map/sys_map Map/sync Map/remap Map/unmap Map/advise Map/protect ```