Archive::Tar(3perl)
π Archive::Tar β the 3perl page, but make it make sense π
okay so real talk: this is Archive::Tar from the Perl Programmers Reference Guide, section 3perl. That's the whole header, bestie, now let's get into it. π
β¨ NAME β¨
Archive::Tar β a module for manipulations of tar archives. yes, tar. the squishy archive format. slay. π¦
β¨ SYNOPSIS β¨
use Archive::Tar;
my $tar = Archive::Tar->new;
$tar->read('origin.tgz');
$tar->extract();
$tar->add_files('file/foo.pl', 'docs/README');
$tar->add_data('file/baz.txt', 'This is the contents now');
$tar->rename('oldname', 'new/file/name');
$tar->chown('/', 'root');
$tar->chown('/', 'root:root');
$tar->chmod('/tmp', '1777');
$tar->write('files.tar'); # plain tar
$tar->write('files.tgz', COMPRESS_GZIP); # gzip compressed
$tar->write('files.tbz', COMPRESS_BZIP); # bzip2 compressed
$tar->write('files.txz', COMPRESS_XZ); # xz compressed
literally the whole vibe in eight lines. iconic.
β¨ DESCRIPTION β¨
Archive::Tar hands you an object oriented way to deal with tar files. It's got class methods for quick-and-easy file wrangling, AND it lets you build whole tar file objects when you wanna do custom stuff. And listen β if you've got the IO::Zlib module installed, Archive::Tar will also support compressed / gzipped tar files. obsessed. β¨
An object of class Archive::Tar represents a .tar(.gz) archive that's full of files and things. that's the whole concept. π«Ά
π₯ Object Methods π₯
Archive::Tar->new( [$file, $compressed] )
Returns a brand new Tar object. If you hand it any arguments, new() will call the read() method for you automatically, passing along whatever args you gave it into read().
β οΈ heads up bestie: ifnew()gets called with arguments andread()fails for any reason,new()returnsundef. no object, no vibes, nothing. π
$tar->read ( $filename|$handle, [$compressed, {opt => 'val'}] )
Reads the given tar file into memory. The first argument can be either the name of a file, or a reference to an already-open filehandle (or an IO::Zlib object if it's compressed).
π BIG WARNING: thereadwill replace any previous content in$tar! not merge, not append. replace. bye to whatever was there.
The second argument may be considered optional, but it's still hanging around for backwards compatibility. Archive::Tar now peeks at the file magic to figure out which class should open the file, and will transparently Do The Right Thing. β¨
<p peach>Archive::Tar will warn if you try to pass a bzip2 / xz compressed file and the IO::Uncompress::Bunzip2 / IO::Uncompress::UnXz are not available β and it'll simply return. no drama, just a warning and a bounce. π
Now for the receipts. You currently cannot pass:
- a
gzipcompressed filehandle that isn't opened withIO::Zlib - a
bzip2compressed filehandle that isn't opened withIO::Uncompress::Bunzip2 - a
xzcompressed filehandle that isn't opened withIO::Uncompress::UnXz - a string containing the full archive information (either compressed or uncompressed)
These are worth while features, but they're not currently implemented. See the "TODO" section if you're nosy. π
The third argument can be a hash reference full of options. Note that all options are case-sensitive. yes ma'am, MD5 β md5.
limitβ Do not read more thanlimitfiles. Super useful if you've got absolutely giant archives and you only care about the first few files. πfilterβ Can be set to a regular expression. Only files with names that match the expression will be read. picky and valid. πmd5β Set to1and the md5sum of files will be returned (instead of file data). like so:
my $iter = Archive::Tar->iter( $file, 1, {md5 => 1} );
while( my $f = $iter->() ) {
print $f->data . "\t" . $f->full_path . $/;
}
extractβ If set to true, immediately extract entries when reading them. This gives you the same memory break as the"extract_archive"function. BUT β note that entries will not be read into memory, they're written straight to disk. Which means noArchive::Tar::Fileobjects are created for you to inspect. you get the files, not the receipts. π
All files are stored internally as Archive::Tar::File objects. Please consult the Archive::Tar::File documentation for details. π
Returns the number of files read in scalar context, and a list of Archive::Tar::File objects in list context. context really said "choose your fighter." β¨
$tar->contains_file( $filename )
Check if the archive contains a certain file. Returns true if the file is in the archive, false otherwise.
π but note, bestie: this function does an exact match using eq on the full path. So it cannot compensate for case-insensitive file-systems, and it won't compare 2 paths to see if they'd point to the same underlying file. it's literal. it's giving "no notes, no nuance."
$tar->extract( [@filenames] )
Writes files whose names are equivalent to any of the names in @filenames to disk, creating subdirectories as necessary. πΈ
This might not work too well under VMS. Under MacPerl, the file's modification time will be converted to the MacOS zero of time, and appropriate conversions will be done to the path. However, the length of each element of the path is not inspected to see whether it's longer than MacOS currently allows (32 characters). so, y'know. be aware. π€·
If extract is called without a list of file names, the entire contents of the archive are extracted.
Returns a list of filenames extracted. π
$tar->extract_file( $file, [$extract_path] )
Write an entry, whose name is equivalent to the file name provided, to disk. Optionally takes a second parameter β the full native path (including filename) that the entry will be written to. π¦
For example:
$tar->extract_file( 'name/in/archive', 'name/i/want/to/give/it' );
$tar->extract_file( $at_file_object, 'name/i/want/to/give/it' );
Returns true on success, false on failure. π
$tar->list_files( [\@properties] )
Returns a list of the names of all the files in the archive.
If list_files() is passed an array reference as its first argument, it returns a list of hash references containing the requested properties of each file. The following list of properties is supported: name, size, mtime (last modified date), mode, uid, gid, linkname, uname, gname, devmajor, devminor, prefix.
Passing an array reference containing only one element, 'name', is special cased to return a list of names rather than a list of hash references β making it equivalent to calling "list_files" without arguments. cute little shortcut, we love her. β¨
$tar->get_files( [@filenames] )
Returns the Archive::Tar::File objects matching the filenames provided. If no filename list was passed, all the Archive::Tar::File objects in the current Tar object are returned. π«Ά
Please refer to the "Archive::Tar::File" documentation on how to handle these objects.
$tar->get_content( $file )
Return the content of the named file. that's it, that's the method. π
$tar->replace_content( $file, $content )
Make the string $content be the content for the file named $file. swapping the insides, keeping the name. π
$tar->rename( $file, $new_name )
Rename the file of the in-memory archive to $new_name.
π note that you must specify a Unix path for $new_name, since per tar standard, all files in the archive must be Unix paths. no exceptions, bestie.
Returns true on success and false on failure. π
$tar->chmod( $file, $mode )
Change mode of $file to $mode.
Returns true on success and false on failure.
$tar->chown( $file, $uname [, $gname] )
Change owner $file to $uname and $gname.
Returns true on success and false on failure.
$tar->remove (@filenamelist)
Removes any entries with names matching any of the given filenames from the in-memory archive. Returns a list of Archive::Tar::File objects that remain. so you get the survivors back. π
$tar->clear
clear clears the current in-memory archive. This effectively gives you a 'blank' object, ready to be filled again. π
Note that clear only has effect on the object, not the underlying tarfile. the disk file is untouched, she's fine, she's thriving.
$tar->write ( [$file, $compressed, $prefix] )
Write the in-memory archive to disk. The first argument can either be the name of a file, or a reference to an already open filehandle (a GLOB reference).
The second argument is used to indicate compression. You can compress using gzip, bzip2 or xz. If you pass a digit, it's assumed to be the gzip compression level (between 1 and 9), but the use of constants is preferred:
# write a gzip compressed file
$tar->write( 'out.tgz', COMPRESS_GZIP );
# write a bzip compressed file
$tar->write( 'out.tbz', COMPRESS_BZIP );
# write a xz compressed file
$tar->write( 'out.txz', COMPRESS_XZ );
β οΈ Note that when you pass in a filehandle, the compression argument is ignored, as all files are printed verbatim to your filehandle. If you wish to enable compression with filehandles, use anIO::Zlib,IO::Compress::Bzip2orIO::Compress::Xzfilehandle instead. choose your filehandle wisely. π
The third argument is an optional prefix. All files will be tucked away in the directory you specify as prefix. So if you have files 'a' and 'b' in your archive, and you specify 'foo' as prefix, they will be written to the archive as 'foo/a' and 'foo/b'. β¨
If no arguments are given, write returns the entire formatted archive as a string β which could be useful if you'd like to stuff the archive into a socket or a pipe to gzip or something. very main character of you. π₯
$tar->add_files( @filenamelist )
Takes a list of filenames and adds them to the in-memory archive.
The path to the file is automatically converted to a Unix like equivalent for use in the archive, and, if on MacOS, the file's modification time is converted from the MacOS epoch to the Unix epoch. So tar archives created on MacOS with Archive::Tar can be read both with tar on Unix and applications like suntar or Stuffit Expander on MacOS. cross-platform queen. π
Be aware that the file's type/creator and resource fork will be lost β which is usually what you want in cross-platform archives. π¦
Instead of a filename, you can also pass it an existing Archive::Tar::File object from, for example, another archive. The object will be clone, and effectively be a copy of the original, not an alias. no secret shared identity, just a twin. π
Returns a list of Archive::Tar::File objects that were just added.
$tar->add_data ( $filename, $data, [$opthashref] )
Takes a filename, a scalar full of data and optionally a reference to a hash with specific options.
Will add a file to the in-memory archive, with name $filename and content $data. Specific properties can be set using $opthashref. The following list of properties is supported: name, size, mtime (last modified date), mode, uid, gid, linkname, uname, gname, devmajor, devminor, prefix, type. (On MacOS, the file's path and modification times are converted to Unix equivalents.) πΈ
Valid values for the file type are the following constants defined by Archive::Tar::Constant:
FILEβ Regular file. the default bestie. πHARDLINK,SYMLINKβ Hard and symbolic ("soft") links;linknameshould specify target. πCHARDEV,BLOCKDEVβ Character and block devices.devmajoranddevminorshould specify the major and minor device numbers. βοΈDIRβ Directory. πFIFOβ FIFO (named pipe). π§SOCKETβ Socket. π
Returns the Archive::Tar::File object that was just added, or undef on failure. π
lowkey that's only the beginning, bestie β the page keeps goingβ¦ π
$tar->error( [$BOOL] ) β gimme the tea on what broke π
Returns the current error string, which is usually just the last error that got reported. If you pass a true value, it hands you the Carp::longmess equivalent of that error β which is basically a full stacktrace, the receipts, the entire call chain, no secrets.
Also, for backwards compatibility the error is still kicking around as $Archive::Tar::error, but bestie⦠please use the method call instead. The variable is giving legacy energy and it's so much safer to just call the method.
$tar->setcwd( $cwd );
okay so real talk: Archive::Tar needs to know the current directory, and it literally runs Cwd::cwd() every single time it extracts a relative entry from the tarfile and saves it into the file system. (As of version 1.30, though, Archive::Tar will use the speed optimization described right below automatically, so this is only relevant if you're using extract_file().)
Since Archive::Tar doesn't change the current directory internally while it's extracting the items in a tarball, all those Cwd::cwd() calls can be skipped entirely β if we can guarantee that the current directory doesn't get changed externally. π
To use this performance boost, set the current directory via
use Cwd;
$tar->setcwd( cwd() );
once before calling a function like extract_file, and Archive::Tar will use that current directory setting from then on and won't call Cwd::cwd() internally anymore. so efficient, we love her.
To switch back to the default behaviour, use
$tar->setcwd( undef );
and Archive::Tar will call Cwd::cwd() internally again, just like before.
If you're using Archive::Tar's extract() method, setcwd() will be called for you automatically. it's handled. periodt. π
π Class Methods π
Archive::Tar->create_archive($file, $compressed, @filelist)
Creates a tar file from the list of files you hand it. The first argument can either be the name of the tar file to create, or a reference to an open file handle (like a GLOB reference β that counts).
The second argument tells it about compression. You can compress with gzip, bzip2, or xz. If you pass a digit, it's assumed to be the gzip compression level (between 1 and 9), but using the constants is preferred, and honestly it's giving main character:
# write a gzip compressed file
Archive::Tar->create_archive( 'out.tgz', COMPRESS_GZIP, @filelist );
# write a bzip compressed file
Archive::Tar->create_archive( 'out.tbz', COMPRESS_BZIP, @filelist );
# write a xz compressed file
Archive::Tar->create_archive( 'out.txz', COMPRESS_XZ, @filelist );
Note that when you pass in a filehandle, the compression argument is ignored, because all files are printed verbatim to your filehandle. So if you actually want compression with filehandles, use an IO::Zlib, IO::Compress::Bzip2, or IO::Compress::Xz filehandle instead. do not come crying to her about it. π
The remaining arguments list the files to be included in the tar file. These files must all exist. Any files which don't exist or can't be read are silently ignored β no warning, no drama, they just vanish from the conversation. π
If the archive creation fails for any reason, create_archive will return false. Please use the error method to find the cause of the failure, because false gives you zero info on its own.
Also note: this method does not write "on the fly", as it were; it still reads all the files into memory before writing out the archive. Consult the FAQ below if this is a problem for you.
Archive::Tar->iter( $filename, [ $compressed, {opt => $val} ] )
Returns an iterator function that reads the tar file without loading it all in memory β iconic memory behaviour, honestly. Each time the function is called it will return the next file in the tarball. The files come back as Archive::Tar::File objects. The iterator function returns the empty list once it has exhausted the files contained. π
The second argument can be a hash reference with options, which are identical to the arguments passed to read().
Example usage:
my $next = Archive::Tar->iter( "example.tar.gz", 1, {filter => qr/\.pm$/} );
while( my $f = $next->() ) {
print $f->name, "\n";
$f->extract or warn "Extraction failed";
# ....
}
Archive::Tar->list_archive($file, $compressed, [\@properties])
Returns a list of the names of all the files in the archive. The first argument can either be the name of the tar file to list, or a reference to an open file handle (e.g. a GLOB reference). name-only is fine, but she can do more π
If list_archive() is passed an array reference as its third argument, it returns a list of hash references containing the requested properties of each file. The following list of properties is supported:
full_pathnamesizemtime(last modified date)modeuidgidlinknameunamegnamedevmajordevminorprefixtype
See Archive::Tar::File for details about supported properties.
Passing an array reference containing only one element, 'name', is special cased to return a list of names rather than a list of hash references. so if you only want names, she knows. π«Ά
Archive::Tar->extract_archive($file, $compressed)
Extracts the contents of the tar file. The first argument can either be the name of the tar file to create, or a reference to an open file handle (e.g. a GLOB reference). All relative paths in the tar file will be created underneath the current working directory. πΈ
extract_archive will return a list of files it extracted. If the archive extraction fails for any reason, extract_archive will return false. Please use the error method to find the cause of the failure, because "false" is not a diagnosis bestie.
$bool = Archive::Tar->has_io_string
Returns true if we currently have IO::String support loaded.
Either IO::String or perlio support is needed to support writing stringified archives. Currently, perlio is the preferred method, if available.
See the GLOBAL VARIABLES section to see how to change this preference.
$bool = Archive::Tar->has_perlio
Returns true if we currently have perlio support loaded.
This requires perl-5.8 or higher, compiled with perlio.
Either IO::String or perlio support is needed to support writing stringified archives. Currently, perlio is the preferred method, if available.
See the GLOBAL VARIABLES section to see how to change this preference.
$bool = Archive::Tar->has_zlib_support
Returns true if Archive::Tar can extract zlib compressed archives. β¨
$bool = Archive::Tar->has_bzip2_support
Returns true if Archive::Tar can extract bzip2 compressed archives. β¨
$bool = Archive::Tar->has_xz_support
Returns true if Archive::Tar can extract xz compressed archives. β¨
Archive::Tar->can_handle_compressed_files
A simple checking routine, which will return true if Archive::Tar is able to uncompress compressed archives on the fly with IO::Zlib, IO::Compress::Bzip2, and IO::Compress::Xz, or false if not both are installed.
You can use this as a shortcut to determine whether Archive::Tar will do what you think before passing compressed archives to its read method. vibe check your setup first, bestie β it saves you a whole meltdown later. π¦
β¨ GLOBAL VARIABLES β¨
Okay bestie, these are the little knobs and dials you can flip before you do stuff β they're package variables, so you set them like $Archive::Tar::WHATEVER = 1; and the module justβ¦ knows. π«Ά
π $Archive::Tar::FOLLOW_SYMLINK
Set this bad boy to 1 and Archive::Tar will effectively make a copy of the file when it extracts β instead of leaving you with a symlink. Default is 0, which means the symlink stays intact, fr. But heads up: you'll have to pack the linked-to file as well, no skipping that part. π
This one gets checked when you write out the tarfile using write or create_archive.
It works just like /bin/tar's -h option. Iconic twin behaviour. π
π $Archive::Tar::CHOWN
By default, Archive::Tar will try to chown your files if it's able to. But sometimes you just don't want that energy, y'know? In that case set this to 0 and it'll disable the chown-ing, even if it were possible.
Default is 1.
π $Archive::Tar::CHMOD
By default, Archive::Tar will try to chmod your files to whatever mode was specified for that particular file in the archive. Some situations? Not the vibe. So set this to 0 to disable chmod-ing entirely.
Default is 1.
π¦ $Archive::Tar::SAME_PERMISSIONS
When $Archive::Tar::CHMOD is enabled, this setting controls whether the permissions on files from the archive get used without modification, or whether they get filtered β by removing any setid bits and applying your current umask.
Default is 1 for the root user and 0 for normal users. Yep, root gets special treatment, as always. π
πΈ $Archive::Tar::DO_NOT_USE_PREFIX
By default, Archive::Tar will try to put paths that are over 100 characters in the prefix field of your tar header, as defined per POSIX-standard. But some (older) tar programs simply do not implement this spec. So to retain compatibility with these older / non-POSIX compliant versions, you can set the $DO_NOT_USE_PREFIX variable to a true value, and Archive::Tar will use an alternate way of dealing with paths over 100 characters β via the GNU Extended Header feature.
β οΈ Note that clients who do not support theGNU Extended Headerfeature will not be able to read these archives. Such clients include tars onSolaris,IrixandAIX. So likeβ¦ choose wisely.
Default is 0.
π₯ $Archive::Tar::DEBUG
Set this to 1 to always get the Carp::longmess output of the warnings, instead of the regular carp. It's the same message you'd get by doing:
$tar->error(1);
Defaults to 0.
π $Archive::Tar::WARN
Set this variable to 0 if you do not want any warnings printed. Personally the author recommends against doing this, but people asked for the option, so here it is. Also, be advised that this is of course not threadsafe. π
Defaults to 1.
π $Archive::Tar::error
Holds the last reported error. Kept for historical reasons, but its use is very much discouraged. Use the error() method instead, bestie:
warn $tar->error unless $tar->extract;
Note that in older versions of this module, the error() method would return an effectively global value even when called as an instance method like above. This has since been fixed, and multiple instances of Archive::Tar now have separate error strings. Slay for progress. β¨
π¨ $Archive::Tar::INSECURE_EXTRACT_MODE
This variable indicates whether Archive::Tar should allow files to be extracted outside their current working directory.
β οΈ Allowing this could have security implications, as a malicious tar archive could alter or replace any file the extracting user has permissions to. Therefor, the default is to not allow insecure extractions.
If you trust the archive, or have other reasons to let the archive write files outside your current working directory, set this variable to "true".
Note that this is a backwards incompatible change from version 1.36 and before. Rip to the old behaviour. π
π $Archive::Tar::EXTRACT_HARDLINK
Prior to version 3.06, Archive::Tar would honour hardlinks in archives. Version 3.06 and onwards will skip hardlinks unless this flag is set. Exercise caution when enabling this. π
π§ $Archive::Tar::HAS_PERLIO
This variable holds a boolean indicating if we currently have perlio support loaded. This will be enabled for any perl greater than 5.8 compiled with perlio.
If you feel strongly about disabling it, set this variable to "false". Note that you will then need IO::String installed to support writing stringified archives.
Don't change this variable unless you really know what you're doing.
β $Archive::Tar::HAS_IO_STRING
This variable holds a boolean indicating if we currently have IO::String support loaded. This will be enabled for any perl that has a loadable IO::String module.
If you feel strongly about disabling it, set this variable to "false". Note that you will then need perlio support from your perl to be able to write stringified archives.
Don't change this variable unless you really know what you're doing. (Yes, same warning as above. They mean it twice. π€)
π
$Archive::Tar::ZERO_PAD_NUMBERS
This variable holds a boolean indicating if we will create zero padded numbers for size, mtime and checksum. The default is 0, indicating that we'll create space padded numbers instead. Added for compatibility with busybox implementations. π«Ά
π Tuning the way RESOLVE_SYMLINK will works
You can tune the behaviour by setting the $Archive::Tar::RESOLVE_SYMLINK variable, or $ENV{PERL5_AT_RESOLVE_SYMLINK} before loading the module Archive::Tar.
Values can be one of the following:
noneβ Disable this mechanism and fail as it was in previous version (<1.88).speed(default) β If you prefer speed, this will read again the whole archive usingread()so all entries will be available.memoryβ If you prefer memory.
Limitation: It won't work for terminal, pipe or sockets or every non seekable source. π
πΈ $Archive::Tar::EXTRACT_BLOCK_SIZE
This variable holds an integer with the block size that should be used when writing files during extraction. It defaults to 1 GiB.
β οΈ Please note that this cannot be arbitrarily large, since some operating systems limit the number of bytes that can be written in one call to write(2), so if this is too large, extraction may fail with an error. So like, don't go feral with it. π
π₯ $Archive::Tar::MAX_FILE_SIZE
This variable holds an upper bound on the per-entry declared size that Archive::Tar will accept when reading an archive. Entries whose header claims a larger size are refused with an error before any read allocation. Defaults to 1 GiB. Set to 0 to disable the cap. π‘οΈ
πΈ FAQ πΈ
Okay so this is the part where everyone slides into the DMs with the same questions. Let's go, bestie. π
π What's the minimum perl version required to run Archive::Tar?
You will need perl version 5.005_03 or newer. That's it, that's the answer.
π Isn't Archive::Tar slow?
Yes it is. Not gonna lie to you. It's pure perl, so it's a lot slower than your /bin/tar.
But β and this is the part everyone forgets β it's very portable. So if speed is the whole vibe for you, consider using /bin/tar instead. No shame in it. π
π§ Isn't Archive::Tar heavier on memory than /bin/tar?
Yes it is, see the previous answer, same energy. Since Compress::Zlib and therefore IO::Zlib doesn't support seek on their filehandles, there is little choice but to read the archive into memory. This is ok if you want to do in-memory manipulation of the archive.
If you just want to extract, use the extract_archive class method instead. It will optimize and write to disk immediately. β¨
Another option is to use the iter class method to iterate over the files in the tarball without reading them all in memory at once. Slay.
π΄ Can you lazy-load data instead?
In some cases, yes. You can use the iter class method to iterate over the files in the tarball without reading them all in memory at once. Same answer, different question, we love a consistent queen.
π How much memory will an X kb tar file need?
Probably more than X kb, since it will all be read into memory. Like, honey, it's all up in there at once. If this is a problem, and you don't need to do in memory manipulation of the archive, consider using the iter class method, or /bin/tar instead.
π½ What do you do with unsupported filetypes in an archive?
Unix has a few filetypes that aren't supported on other platforms, like Win32. If we encounter a hardlink or symlink we'll just try to make a copy of the original file, rather than throwing an error. Be nice, make a copy, move on.
This does require you to read the entire archive in to memory first, since otherwise we wouldn't know what data to fill the copy with. (This means that you cannot use the class methods, including iter on archives that have incompatible filetypes and still expect things to work).
For other filetypes, like chardevs and blockdevs we'll warn that the extraction of this particular item didn't work. Not a crash, just a lil warning. π«Ά
π I'm using WinZip, or some other non-POSIX client, and files are not being extracted properly!
Bestie, I feel you. By default, Archive::Tar is in a completely POSIX-compatible mode, which uses the POSIX-specification of tar to store files. For paths greater than 100 characters, this is done using the POSIX header prefix. Non-POSIX-compatible clients may not support this part of the specification, and may only support the GNU Extended Header functionality. To facilitate those clients, you can set the $Archive::Tar::DO_NOT_USE_PREFIX variable to true. See the GLOBAL VARIABLES section for details on this variable.
Note that GNU tar earlier than version1.14does not cope well with thePOSIX header prefix. If you use such a version, consider setting the$Archive::Tar::DO_NOT_USE_PREFIXvariable totrue.
π How do I extract only files that have property X from an archive?
Sometimes, you might not wish to extract a complete archive, just the files that are relevant to you, based on some criteria. Valid. Very main character of you.
You can do this by filtering a list of Archive::Tar::File objects based on your criteria. For example, to extract only files that have the string foo in their title, you would use:
$tar->extract(
grep { $_->full_path =~ /foo/ } $tar->get_files
);
This way, you can filter on any attribute of the files in the archive. Consult the Archive::Tar::File documentation on how to use these objects. Iykyk. π
ποΈ How do I access .tar.Z files?
The Archive::Tar module can optionally use Compress::Zlib (via the IO::Zlib module) to access tar files that have been compressed with gzip. Unfortunately tar files compressed with the Unix compress utility cannot be read by Compress::Zlib and so cannot be directly accesses by Archive::Tar. (yes, "accesses", that's the original typo, we're keeping it, it's iconic β¨)
If the uncompress or gunzip programs are available, you can use one of these workarounds to read .tar.Z files from Archive::Tar
Firstly with uncompress
use Archive::Tar;
open F, "uncompress -c $filename |";
my $tar = Archive::Tar->new(*F);
...
and this with gunzip
use Archive::Tar;
open F, "gunzip -c $filename |";
my $tar = Archive::Tar->new(*F);
...
Similarly, if the compress program is available, you can use this to write a .tar.Z file
use Archive::Tar;
use IO::File;
my $fh = IO::File->new( "| compress -c >$filename" );
my $tar = Archive::Tar->new();
...
$tar->write($fh);
$fh->close ;
π How do I handle Unicode strings?
Big one. Sit down. Archive::Tar uses byte semantics for any files it reads from or writes to disk. This is not a problem if you only deal with files and never look at their content or work solely with byte strings. But if you use Unicode strings with character semantics, some additional steps need to be taken.
For example, if you add a Unicode string like
# Problem
$tar->add_data('file.txt', "Euro: \x{20AC}");
then there will be a problem later when the tarfile gets written out to disk via $tar->write():
Wide character in print at .../Archive/Tar.pm line 1014.
The data was added as a Unicode string and when writing it out to disk, the :utf8 line discipline wasn't set by Archive::Tar, so Perl tried to convert the string to ISO-8859 and failed. The written file now contains garbage. π
For this reason, Unicode strings need to be converted to UTF-8-encoded bytestrings before they are handed off to add_data():
use Encode;
my $data = "Accented character: \x{20AC}";
$data = encode('utf8', $data);
$tar->add_data('file.txt', $data);
A opposite problem occurs if you extract a UTF8-encoded file from a tarball. Using get_content() on the Archive::Tar::File object will return its content as a bytestring, not as a Unicode string.
If you want it to be a Unicode string (because you want character semantics with operations like regular expression matching), you need to decode the UTF8-encoded content and have Perl convert it into a Unicode string:
use Encode;
my $data = $tar->get_content();
# Make it a Unicode string
$data = decode('utf8', $data);
There is no easy way to provide this functionality in Archive::Tar, because a tarball can contain many files, and each of which could be encoded in a different way. Yeah. That's just how it is, bestie. π
π CAVEATS π
The AIX tar does not fill all unused space in the tar archive with 0x00. This sometimes leads to warning messages from Archive::Tar.
Invalid header block at offset nnn
A fix for that problem is scheduled to be released in the following levels of AIX, all of which should be coming out in the 4th quarter of 2009:
AIX 5.3 TL7 SP10
AIX 5.3 TL8 SP8
AIX 5.3 TL9 SP5
AIX 5.3 TL10 SP2
AIX 6.1 TL0 SP11
AIX 6.1 TL1 SP7
AIX 6.1 TL2 SP6
AIX 6.1 TL3 SP3
The IBM APAR number for this problem is IZ50240 (Reported component ID: 5765G0300 / AIX 5.3). It is possible to get an ifix for that problem. If you need an ifix please contact your local IBM AIX support. π
π§ TODO π§
(the author's wishlist, not instructions for you, ok?)
Check if passed in handles are open for read/write
Currently I don't know of any portable pure perl way to do this. Suggestions welcome. π
Allow archives to be passed in as string
Currently, we only allow opened filehandles or filenames, but not strings. The internals would need some reworking to facilitate stringified archives.
Facilitate processing an opened filehandle of a compressed archive
Currently, we only support this if the filehandle is an IO::Zlib object. Environments, like apache, will present you with an opened filehandle to an uploaded file, which might be a compressed archive.
π SEE ALSO π
The GNU tar specification
<https://www.gnu.org/software/tar/manual/tar.html>
The PAX format specification
The specification which tar derives from; <https://pubs.opengroup.org/onlinepubs/007904975/utilities/pax.html>
π«Ά AUTHOR π«Ά
This module by Jos Boumans <kane@cpan.org>.
Please reports bugs to <bug-archive-tar@rt.cpan.org>.
π ACKNOWLEDGEMENTS π
Thanks to Sean Burke, Chris Nandor, Chip Salzenberg, Tim Heaney, Gisle Aas, Rainer Tammer and especially Andrew Savige for their help and suggestions. Legends, all of them. π
π COPYRIGHT π
This module is copyright (c) 2002 - 2009 Jos Boumans <kane@cpan.org>. All rights reserved.
This library is free software; you may redistribute and/or modify it under the same terms as Perl itself.
okay that's literally the whole page, you ate it, periodt. π
β¨ This was Archive::Tar(3perl) from perl v5.44.0, dated 2026-10-17 β go forth and tar responsibly, bestie ππ¦
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms