File::Map(3pm)
File::Map(3pm) β from the User Contributed Perl Documentation, and bestie, it's literally "Memory mapping made simple and safe."
π NAME π
File::Map - Memory mapping made simple and safe.
πΈ VERSION πΈ
version 0.71
β¨ SYNOPSIS β¨
use File::Map 'map_file';
map_file my $map, $filename, '+<';
$map =~ s/bar/quz/g;
substr $map, 1024, 11, "Hello world";
π¦ DESCRIPTION π¦
File::Map maps files or anonymous memory into perl variables. Iconic.
π Advantages of memory mapping π
- Unlike normal perl variables, mapped memory is (usually) shared between threads or forked processes. The way that works is genuinely giving main character energy.
- It is an efficient way to slurp an entire file. Unlike for example
File::Slurp, this module returns almost immediately, loading the pages lazily on access. This means you only 'pay' for the parts of the file you actually use. - Perl usually doesn't return memory to the system while running, mapped memory can be returned.
π Advantages of this module over other similar modules π
- Safety and Speed β This module is safe yet fast. Alternatives are either fast but can cause segfaults or lose the mapping when not used correctly, or are safe but rather slow.
File::Mapis as fast as a normal string yet safe. - Simplicity β It offers a simple interface targeted at common usage patterns:
- Files are mapped into a variable that can be read just like any other variable, and it can be written to using standard Perl techniques such as regexps and
substr. - Files can be mapped using a set of simple functions. There is no need to know weird constants or the order of 6 arguments.
- It will automatically unmap the file when the scalar gets destroyed. This works correctly even in multi-threaded programs.
- Files are mapped into a variable that can be read just like any other variable, and it can be written to using standard Perl techniques such as regexps and
- Portability β
File::Mapsupports Unix and Windows. - Thread synchronization β It has built-in support for thread synchronization.
π₯ FUNCTIONS π₯
π Mapping π
The following functions for mapping a variable are available for exportation. Note that all of these functions throw exceptions on errors, unless noted otherwise. Periodt.
map_handle $lvalue, $filehandle, $mode = '<', $offset = 0, $length = -s(*handle) - $offsetβ Use a filehandle to map into an lvalue.$filehandleshould be a scalar filehandle.$modeuses the same format asopendoes (it currently accepts<,+<,>and+>).$offsetand$lengthare byte positions in the file, and default to mapping the whole file.map_file $lvalue, $filename, $mode = '<', $offset = 0, $length = -s($filename) - $offsetβ Open a file and map it into an lvalue. Other than$filename, all arguments work as inmap_handle.map_anonymous $lvalue, $length, $typeβ Map an anonymous piece of memory.$typecan be either'shared', in which case it will be shared with child processes, or'private', which won't be shared.sys_map $lvalue, $length, $protection, $flags, $filehandle, $offset = 0β Low level map operation. It accepts the same constants asmmapdoes (except its first argument obviously). If you don't know howmmapworks you probably shouldn't be using this.unmap $lvalueβ Unmap a variable. Note that normally this is not necessary as variables are unmapped automatically at destruction, but it is included for completeness.remap $lvalue, $new_sizeβ Try to remap$lvalueto a new size. This call is linux specific and not supported on other systems. For a file backed mapping a file must be long enough to hold the new size, otherwise you can expect bus faults. For an anonymous map it must be private, shared maps can not be remapped. Use with caution.
π§ Auxiliary π§
sync $lvalue, $synchronous = 1β Flush changes made to the memory map back to disk. Mappings are always flushed when unmapped, so this is usually not necessary. If$synchronousis true and your operating system supports it, the flushing will be done synchronously.pin $lvalueβ Disable paging for this map, thus locking it in physical memory. Depending on your operating system there may be limits on pinning.unpin $lvalueβ Unlock the map from physical memory.advise $lvalue, $adviceβ Advise a certain memory usage pattern. This is not implemented on all operating systems, and may be a no-op. The following values for$adviceare always accepted:.normalβ Specifies that the application has no advice to give on its behavior with respect to the mapped variable. It is the default characteristic if no advice is given.randomβ Specifies that the application expects to access the mapped variable in a random order.sequentialβ Specifies that the application expects to access the mapped variable sequentially from start to end.willneedβ Specifies that the application expects to access the mapped variable in the near future.dontneedβ Specifies that the application expects that it will not access the mapped variable in the near future.
On some systems there may be more values available, but this can not be relied on. Unknown values for $advice will cause a warning but are further ignored.
protect $lvalue, $modeβ Change the memory protection of the mapping.$modetakes the same format asopen, but also acceptssys_mapstyle constants.
β Locking β
These locking functions provide locking for threads for the mapped region. The mapped region has an internal lock and condition variable. The condition variable functions(wait_until, notify, broadcast) can only be used inside a locked block. If your perl has been compiled without thread support the condition functions will not be available.
lock_map $lvalueβ Lock$lvalueuntil the end of the scope. If your perl does not support threads, this will be a no-op.wait_until { block } $lvalueβ Wait for block to become true. After every failed attempt, wait for a signal. It returns the value returned by the block.notify $lvalueβ This will signal to one listener that the map is available.broadcast $lvalueβ This will signal to all listeners that the map is available.
π Constants π
PROT_NONE, PROT_READ, PROT_WRITE, PROT_EXEC, MAP_ANONYMOUS, MAP_SHARED, MAP_PRIVATE, MAP_ANON, MAP_FILE
These constants are used for sys_map. If you think you need them your mmap manpage will explain them, but in most cases you can skip sys_map altogether.
π«Ά EXPORTS π«Ά
All previously mentioned functions are available for exportation, but none are exported by default. Some functions may not be available on your OS or your version of perl as specified above. A number of tags are defined to make importation easier.
:mapβmap_handle,map_file,map_anonymous,sys_map,unmap:extraβremap,sync,pin,unpin,advise,protect:lockβlock_map,wait_until,notify,broadcast:constantsβPROT_NONE,PROT_READ,PROT_WRITE,PROT_EXEC,MAP_ANONYMOUS,MAP_SHARED,MAP_PRIVATE,MAP_ANON,MAP_FILE:allβ All functions defined in this module.
π DIAGNOSTICS π
π Exceptions π
Could not <function name>: this variable is not memory mappedβ An attempt was made tosync,remap,unmap,pin,unpin,adviseorlock_mapan unmapped variable.Could not <function name>: <system error>β Your OS didn't allowFile::Mapto do what you asked it to do for some reason.Trying to <function_name> on an unlocked mapβ You tried towait_until,notifyorbroadcaston an unlocked variable.Zero length not allowed for anonymous mapβ A zero length anonymous map is not possible (or in any way useful).Can't remap a shared mappingβ An attempt was made to remap a mapping that is shared among different threads, this is not possible.Window (<start>, <end>) is outside the fileβ The offset and/or length you specified were invalid for this file.Can't map fake filehandleβ The filehandle you provided is not real. This may mean it's a scalar string handle or a tied handle.No such flag <flag_name>β The flag given formap_anonymousisn't valid, it should either besharedorprivate.
π Warnings π
Writing directly to a memory mapped file is not recommendedβ Due to the way perl works internally, it's not possible to write a mapping implementation that allows direct assignment yet performs well. As a compromise,File::Mapis capable of fixing up the mess if you do it nonetheless, but it will warn you that you're doing something you shouldn't. This warning is only given whenuse warnings 'substr'is in effect.Truncating new value to size of the memory mapβ This warning is additional to the previous one, warning you that you're losing data. This warning is only given whenuse warnings 'substr'is in effect.Shouldn't mmap non-binary filehandleβ You tried to map a filehandle that has some encoding layer. Encoding layers are not supported byFile::Map. This warning is only given whenuse warnings 'layer'is in effect. Note that this may become an exception in a future version.Unknown advice '<advice>'β You gaveadvisean advice it didn't know. This is either a typo or a portability issue. This warning is only given whenuse warnings 'portable'is in effect.Syncing a readonly map makes no senseβsyncflushes changes to the map to the filesystem. This obviously is of little use when you can't change the map. This warning is only given whenuse warnings 'io'is in effect.Can't overwrite an empty mapβ Overwriting an empty map is rather nonsensical, hence a warning is given when this is tried. This warning is only given whenuse warnings 'substr'is in effect.
π DEPENDENCIES π
This module depends on perl 5.8 and Sub::Exporter::Progressive. Perl 5.8.8 or higher is recommended because older versions can give spurious warnings.
In perl versions before 5.11.5 many string functions including substr are limited to 32bit logic http://rt.perl.org/rt3//Public/Bug/Display.html?id=72784, even on 64bit architectures. Effectively this means you can't use them on strings bigger than 2GB. If you are working with such large files, it is strongly recommended to upgrade to 5.12.
In perl versions before 5.17.5, there is an off-by-one bug in Perl's regexp engine, as explained here http://rt.perl.org/rt3//Public/Bug/Display.html?id=73542. If the length of the file is an exact multiple of the page size, some regexps can trigger a segmentation fault.
π PITFALLS π
Okay bestie, listen up, this is the part where we hold hands and read the warnings together, because these ones lowkey bite π«Ά
- This module doesn't do any encoding or newline transformation for you, and it will straight-up reject any filehandle with those features enabled β because mapping it would return a different value than reading it normally would. Like, it's not being dramatic, it's just correct. Most importantly, this means on Windows you have to remember to use the
":raw"open mode orbinmodeto make your filehandles binary before mapping them, because by default it would do"crlf"transformation π. See PerlIO for more information on how that works. - You can map a
":utf8"filehandle, but writing to it may be tricky. Hic sunt dracones. π (that's latin for "here be dragons," and yeah, it's giving map-edge energy) - You probably don't want to use
">"as a mode. This does not give you reading permissions on many architectures, resulting in segmentation faults when trying to read a variable π (confusingly, it will work on some others like x86 β do not let that fool you, that's not a vibe check you want to pass π)
π BUGS AND LIMITATIONS π
As any piece of software, bugs are likely to exist here. Bug reports are welcome, fr fr π
Please report any bugs or feature requests to bug-file-map at rt.cpan.org, or through the web interface at <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=File-Map>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes π
Known limitation alert π¨: Unicode file mappings are known to be buggy on perl 5.8.7 and lower.
π¦ SEE ALSO π¦
- Sys::Mmap, the original Perl mmap module β the OG, respect it π
- mmap(2), your mmap man page β go read the source of truth bestie
- Win32::MMF
- CreateFileMapping at MSDN: <http://msdn.microsoft.com/en-us/library/aa366537(VS.85).aspx>
πΈ AUTHOR πΈ
Leon Timmermans <fawaka@gmail.com> β icon, legend, the moment β¨
π COPYRIGHT AND LICENSE π
This software is copyright (c) 2008 by Leon Timmermans.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Slay, honestly π«Ά
And that's the whole page, bestie!! π You just read File::Map(3pm) in full β this copy came from perl v5.42.0, dated 2023-04-11, so if your local version is different, no cap, go check your own man page π
Go map some files, stay ":raw", and remember: the dragons are only in the ":utf8" writing part ππ
π¦ where this page comes from
- opensuse-leap 16.0: perl-File-Map 0.71-bp160.1.12 Β· Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-File-Map 0.71-bp160.1.12 Β· Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-File-Map 0.71-bp160.1.12 Β· Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-File-Map 0.71-bp160.1.12 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms