Badger...::Path(3pm)

๐Ÿ“ฆ
version 0.16 ยท 4 versions
, in debian trixie, ubuntu noble, ubuntu resolute

๐Ÿ’– Badger::Filesystem::Path(3pm) ๐Ÿ’–

okay so this is the User Contributed Perl Documentation page for Badger::Filesystem::Path โ€” the generic filesystem path object. bestie, this is part 1, so grab a strawberry drink ๐Ÿ“ and let's get into it.


โœจ NAME โœจ

Badger::Filesystem::Path โ€” generic filesystem path object


๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

# using Badger::Filesytem constructor subroutine
use Badger::Filesystem 'Path';

# use native OS-specific paths:
$path = Path('/path/to/something');

# or generic OS-independant paths
$path = Path('path', 'to', 'something');

# manual object construction
use Badger::Filesystem::Path;

# positional arguments
$path = Badger::Filesystem::Path->new('/path/to/something');
$path = Badger::Filesystem::Path->new(['path', 'to', 'something']);

# named parameters
$path = Badger::Filesystem::Path->new(
    path => '/path/to/something'
);
$path = Badger::Filesystem::Path->new(
    path => ['path', 'to', 'something']
);

# path inspection methods
$path->path;                    # current path
$path->base;                    # parent directory or path itself
$path->parent;                  # directory object for base
$path->extension                # filename .XXX extension
$path->basename                 # filename without .XXX extension
$path->is_absolute;             # path is absolute
$path->is_relative;             # path is relative
$path->exists;                  # returns true/false
$path->must_exist;              # throws error if not
@stats = $path->stat;           # returns list
$stats = $path->stat;           # returns list ref

# path translation methods
$path->relative;                # relative to cwd
$path->relative($base);         # relative to $base
$path->absolute;                # relative to filesystem root
$path->definitive;              # physical file location
$path->collapse;                # resolve '.' and '..' in $path

# path comparison methods
$path->above($another_path);    # $path is ancestor of $another_path
$path->below($another_path);    # $path is descendant of $another_path

๐ŸŒธ INTRODUCTION ๐ŸŒธ

so this is the documentation for the Badger::Filesystem::Path module. It defines a base class object for the Badger::Filesystem::File and Badger::Filesystem::Directory objects โ€” those two inherit the methods below, and sometimes they redefine them.

in other words, you should read this documentation first if you're working with Badger::Filesystem::File or Badger::Filesystem::Directory objects. it's giving blueprint energy ๐Ÿ‘‘


๐Ÿ‘‘ DESCRIPTION ๐Ÿ‘‘

The Badger::Filesystem::Path module defines a base class object for representing paths in a real or virtual file system.

You can create a generic path object โ€” like, one that doesn't relate to a specific file or directory in a file system โ€” using the Path constructor method in Badger::Filesystem.

use Badger::Filesystem 'Path';

my $path = Path('/path/to/something');

However, in most cases you'll want to create a file or directory subclass object. The easiest way to do that is like this:

use Badger::Filesystem 'File Path';

my $file = File('/path/to/file');
my $dir  = Dir('/path/to/dir');

If you're concerned about portability to other operating systems and/or file systems, then you can specify paths as a list or reference to a list of component names.

my $file = File('path', 'to', 'file');
my $dir  = Dir(['path', 'to', 'dir']);

๐Ÿ’… METHODS ๐Ÿ’…

๐Ÿ’– new($path)

Constructor method to create a new Badger::Filesystem::Path object. The path can be specified as a single positional argument, either as a text string or reference to list of path components.

# single text string
$path = Badger::Filesystem::Path->new('/path/to/something');

# reference to list
$path = Badger::Filesystem::Path->new(['path', 'to', 'something']);

It can also be specified as a path named parameter.

# named parameter list
$path = Badger::Filesystem::Path->new(
    path => '/path/to/something'
);

# reference to hash of named parameter(s)
$path = Badger::Filesystem::Path->new({
    path => '/path/to/something'
});

The constructor method also recognises the filesystem named parameter which can contain a reference to the Badger::Filesystem object or class that created it. In most cases you can rely on the Badger::Filesystem to create path objects for you, using either the path() method, or the Path() subroutine.

use Badger::Filesystem 'FS Path';

# FS is alias for 'Badger::Filesystem'
# Path() is constructor subrooutine
my $path;

# using the path() method
$path = FS->path('/path/to/something');
$path = FS->path('path', 'to', 'something');
$path = FS->path(['path', 'to', 'something']);

# using the Path() subroutine
$path = Path('/path/to/something');
$path = Path('path', 'to', 'something');
$path = Path(['path', 'to', 'something']);

The examples that follow will use the Path() constructor subroutine.

๐Ÿงš init(%config)

Default initialisation method which subclasses โ€” e.g. Badger::Filesystem::Directory and Badger::Filesystem::File โ€” can redefine.

๐ŸŽ€ path()

This method returns the path as a text string. It is called automatically whenever the path object is stringified. literally the moment it becomes a string, this kicks in โœจ

๐ŸŒˆ is_absolute()

Returns true if the path is absolute, false if not.

๐ŸŒˆ is_relative()

Returns true if the path is relative, false if not.

๐Ÿ’ซ absolute($base)

Returns an absolute representation of the path, relative to the $base path passed as an argument, or the current working directory if $base is not specified.

# assume cwd is /foo/bar,
my $path = Path('/baz/bam');

print $path->absolute;                  # /foo/bar/baz/bam
print $path->absolute('/wiz');          # /wiz/baz/bam

๐Ÿ’ซ relative($base)

Returns a relative representation of the path, relative to the $base path passed as an argument, or the current working directory if $base is not specified.

# assume cwd is /foo/bar,
my $path = Path('/foo/bar/baz/bam');

print $path->relative;                  # /baz/bam
print $path->relative('/foo');          # /bar/baz/bam

๐Ÿ”ฎ definitive()

Returns the definitive representation of the path which in most cases will be the same as the absolute() path.

However, if you're using a virtual filesystem, then the definitive path will include the virtual root directory, whereas a the absolute path will not.

my $vfs  = Badger::Filesystem::Virtual->new( root => '/my/vfs' );
my $path = $vfs->file('/foo/bar');
print $path->absolute;              # /foo/bar
print $path->definitive;            # /my/vfs/foo/bar

๐Ÿ‘‘ canonical()

This method returns the canonical representation of the path. In most cases this is the same as the absolute path โ€” in fact the base class aliases the canonical() method directly to the absolute() method.

print Path('foo')->canonical;               # /your/current/path/foo
print Path('/foo/bar')->canonical;          # /foo/bar
print Path('/foo/bar/')->canonical;         # /foo/bar
print Path('/foo/bar.txt')->canonical;      # /foo/bar.txt

Note that the Badger::Filesystem::Path base class will remove any trailing slashes โ€” or whatever the appropriate directory separator is for your filesystem โ€” from the end of an absolute path.

In the case of directories, implemented by the Badger::Filesystem::Directory subclass, a trailing slash โ€” or relevant separator for your filesystem โ€” will be added.

print Dir('/foo/bar')->canonical;          # /foo/bar/

This is done by delegation to the slash_directory() method in Badger::Filesystem.

๐ŸŒ€ collapse()

Reduces the path to its simplest form by resolving and removing any "." (current directory) and ".." (parent directory) components โ€” or whatever the corresponding tokens are for the current and parent directories of your filesystem.

my $path = Path('/foo/bar/../baz')->collapse;
print $path;   # /foo/baz

See the collapse_dir() method in Badger::Filesystem for further information.

๐Ÿฆ‹ above($child)

Returns true if the path is "above" the $child path passed as an argument. Formally, we say that the path is an ancestor of $child meaning that it is the parent directory, or grand-parent, or great-grand-parent, and so on.

my $parent = Path('/foo/bar');
my $child  = Path('/foo/bar/baz');
$parent->above($child);                 # true

This is implemented as a simple prefix match. That is, the parent path must appear at the start of the child path. Consequently, this method will not account for symbolic links or other similar filesystem features, and it may not work properly on systems that don't follow this convention โ€” although there are none that I'm aware of.

๐Ÿฆ‹ below($parent)

Returns true if the path is "below" the $parent path passed as an argument. Formally, we say that the path is a descendant of $parent meaning that it is an immediate sub-directory, or sub-sub-directory, and so on.

my $parent = Path('/foo/bar');
my $child  = Path('/foo/bar/baz');
$child->below($parent);                 # true

Like above(), this is implemented using a simple prefix match.

๐ŸŒฑ base()

Returns the base directory of a path. For Badger::Filesystem::Path and Badger::Filesystem::Directory objects, this method will return the complete path.

print Path('/foo/bar')->base;           # /foo/bar
print Directory('/foo/bar')->base;      # /foo/bar

However the Badger::Filesystem::File module returns the parent directory in which the file is located.

print File('/foo/bar')->base;           # /foo

๐ŸŒŸ parent($skip_generations) / up($skip_generations)

Returns a Badger::Filesystem::Directory object representing the parent directory for a path.

Path->('/foo/bar')->parent;             # path object for /foo

A numerical argument can be provided to indicate the number of generation you want to skip. A value of 0 is the same as providing no argument โ€” it returns the parent. A value of 1 skips the parent and returns the grand-parent, and so on.

Path->('/foo/bar/baz/bam')->parent(2);  # path object for /foo

The root directory will be returned if you try to skip too many generations.

Path->('/foo/bar/baz/bam')->parent(20); # path object for /

โœจ path_up() โœจ

Okay bestie, this one hands you back a text string that's the parent of a path. The way it works:

  • If your path has multiple items (like /foo/bar or foo/bar), the last item gets yeeted (so you get /foo or foo respectively). Gone. Not invited. ๐Ÿ’…
  • If an absolute path has one item or none (like /foo or /), you get the root directory (/) back. Iconic.
  • If it's a relative path with only one item (like foo), it's assumed to be relative to the current working directory โ€” so the current working directory gets returned (like /path/to/current/dir). Main character behavior fr fr.

๐ŸŒธ exists() ๐ŸŒธ

Returns true if the path actually exists in the filesystem (as a file, a directory, or some other entry), and false if it doesn't. Vibe check on your filesystem, basically:

if ($path->exists) {
    print "$path already exists\n";
}
else {
    print "Creating $path\n";
    # ...etc...
}

๐Ÿซถ must_exist($create) ๐Ÿซถ

Checks that the path exists (by calling exists()) and throws an error if it doesn't. No chill, no mercy:

$path->must_exist;                      # no need to check return value

The $create flag can be set to have it attempt to create() itself if it doesn't already exist. But lowkey this only makes sense for file and directory subclasses, not base class paths:

$dir->must_exist(1);                    # create if it doesn't

๐Ÿ’€ create() ๐Ÿ’€

In the base class this method will throw an error. Periodt. You literally can't physically create an abstract path unless you know what kind of concrete entity (like a file or directory) it maps onto. In other words, create() only works for the Badger::Filesystem::File and Badger::Filesystem::Directory subclasses:

$path->create;                          # FAIL
$dir->create;                           # OK
$file->create;                          # OK

๐ŸŽ€ chmod($perms) ๐ŸŽ€

Changes the file permissions on a file or directory:

$file->chmod(0775);

๐Ÿ”ฅ stat() ๐Ÿ”ฅ

Performs a filesystem "stat" on the path and returns a list (in list context), or a reference to a list (in scalar context), containing the 13 information elements:

@list = $path->stat;                    # list context
$list = $path->stat;                    # scalar context

A summary of the fields is below, bestie. See perldoc -f stat for complete details. Each of the individual fields can also be accessed via their own methods, also listed:

  • 0 โ€” device() โ€” device number of filesystem
  • 1 โ€” inoode() โ€” inode number
  • 2 โ€” mode() โ€” file mode (type and permissions)
  • 3 โ€” links() โ€” number of (hard) links to the file
  • 4 โ€” user() โ€” numeric user ID of file's owner
  • 5 โ€” group() โ€” numeric group ID of file's owner
  • 6 โ€” device_type() โ€” the device identifier (special files only)
  • 7 โ€” size() โ€” total size of file, in bytes
  • 8 โ€” atime() โ€” last access time in seconds since the epoch
  • 9 โ€” mtime() โ€” last modify time in seconds since the epoch
  • 10 โ€” ctime() โ€” inode change time in seconds since the epoch (*)
  • 11 โ€” block_size() โ€” preferred block size for file system I/O
  • 12 โ€” blocks() โ€” actual number of blocks allocated

In addition to those that are returned by Perl's inbuilt stat function, this method returns four additional flags:

  • 13 โ€” readable() โ€” file is readable by current process
  • 14 โ€” writeable() โ€” file is writeable by current process
  • 15 โ€” executable() โ€” file is executable by current process
  • 16 โ€” owner() โ€” file is owned by current process

๐Ÿฆ‹ stats() ๐Ÿฆ‹

A wrapper around the stat() method which caches the results to avoid making repeated filesystem calls. Your filesystem said "please stop asking me the same thing":

@list = $path->stats;                   # list context
$list = $path->stats;                   # scalar context
Note that the accessed(), created() and modified() methods also cache the Badger::Timestamp objects they create to represent the access, creation and modification times respectively.

๐ŸŒˆ restat() ๐ŸŒˆ

Clears any cached values stored by the stats(), accessed(), created() and modified() methods and calls stats() to reload (and re-cache) the data from a stat() call. Fresh start energy โœจ


๐Ÿ‘‘ device() ๐Ÿ‘‘

Returns the device number for the file. See stat().


โญ inode() โญ

Returns the inode number for the file. See stat().


๐Ÿ’œ mode() ๐Ÿ’œ

Returns the file mode for the file. Note that this contains both the file type and permissions. See stat().


๐Ÿ“ permissions() / perms() ๐Ÿ“

Returns the file permissions. This is equivalent to $file->mode & 0777.


Returns the number of hard links to the file. See stat().


๐ŸŒธ user() ๐ŸŒธ

Returns the numeric user ID of the file's owner. See stat().


๐Ÿ’– group() ๐Ÿ’–

Returns the numeric group ID of the file's group. See stat().


๐Ÿ’… device_type() ๐Ÿ’…

Returns the device identifier (for special files only). See stat().


๐Ÿ”ฅ size() ๐Ÿ”ฅ

Returns the total size of the file in bytes. See stat().


๐ŸŽ€ atime() ๐ŸŽ€

Returns the time (in seconds since the epoch) that the file was last accessed. See stat().


๐Ÿซถ accessed() ๐Ÿซถ

Returns a Badger::Timestamp object for the atime() value. This object will auto-stringify to produce an ISO-8601 formatted date. You can also call various methods to access different parts of the time and/or date:

print $file->accessed;              # 2009/04/20 16:25:00
print $file->accessed->date;        # 2009/04/20
print $file->accessed->year;        # 2009

๐Ÿ’€ mtime() ๐Ÿ’€

Returns the time (in seconds since the epoch) that the file was last modified. See stat().


๐Ÿฆ‹ modified() ๐Ÿฆ‹

Returns a Badger::Timestamp object for the mtime() value:

print $file->modified;              # 2009/04/20 16:25:00
print $file->modified->time;        # 16:25:0
print $file->modified->hour;        # 16

๐ŸŒˆ ctime() ๐ŸŒˆ

Returns the time (in seconds since the epoch) that the file was created. See stat().


๐Ÿ‘‘ created() ๐Ÿ‘‘

Returns a Badger::Timestamp object for the ctime() value:

print $file->created;               # 2009/04/20 16:25:00
print $file->created->date;         # 2009/04/20
print $file->created->time;         # 16:25:00

โญ block_size() โญ

Returns the preferred block size for file system I/O on the file. See stat().


๐Ÿ’œ blocks() ๐Ÿ’œ

Returns the actual number of blocks allocated to the file. See stat().


๐Ÿ“ readable() ๐Ÿ“

Returns a true value if the file is readable by the current user (i.e. the owner of the current process), false if not. See stat().


๐Ÿงš writeable() ๐Ÿงš

Returns a true value if the file is writeable by the current user (i.e. the owner of the current process), false if not. See stat().


๐ŸŒธ executable() ๐ŸŒธ

Returns a true value if the file is executable by the current user (i.e. the owner of the current process), false if not. See stat().


๐Ÿ’– owner() ๐Ÿ’–

Returns a true value if the file is owned by the current user (i.e. the owner of the current process), false if not. See stat().


๐Ÿ’… filesystem() ๐Ÿ’…

Returns a reference to a Badger::Filesystem object, or the name of the filesystem class (e.g. Badger::Filesystem or a subclass) that created the path object. If this is undefined then the default value defined in the $FILESYSTEM class variable is returned. Unless you've changed it, or re-defined it in a subclass, this value will be Badger::Filesystem.

The end result is that you can use the filesystem method to access a Badger::Filesystem object or class through which you can perform other filesystem related operations. This is used internally by a number of method:

# access filesystem via existing path
$path->filesystem->dir('/a/new/directory/object');

# same as
Badger::Filesystem->dir('/a/new/directory/object');

๐Ÿ”ฅ visit($visitor) ๐Ÿ”ฅ

Entry point for a filesystem visitor to visit a filesystem path. A reference to a Badger::Filesystem::Visitor object (or subclass) should be passed as the first argument:

use Badger::Filesystem::Visitor;

my $visitor = Badger::Filesystem::Visitor->new( recurse => 1 );
$path->visit($visitor);

Alternately, a list or reference to a hash array of named parameters may be provided. These will be used to instantiate a new Badger::Filesystem::Visitor object (via the Badger::Filesystem visitor() method) which will then be applied to the path. If no arguments are passed then a visitor is created with a default configuration:

# either list of named params
$path->visit( recurse => 1 );

# or reference to hash array
$path->visit({ recurse => 1});

The method then calls the visitor visit() passing $self as an argument to begin the visit.


๐ŸŽ€ accept($visitor) ๐ŸŽ€

This method is called to dispatch a visitor to the correct method for a filesystem object. In the Badger::Filesystem::Path base class, it calls the visitor visit_path() method, passing the $self object reference as an argument. Subclasses redefine this method to call other visitor methods.


๐Ÿซถ enter($visitor) ๐Ÿซถ

This is a special case of the accept() method which subclasses (e.g. directory) use to differentiate between the initial entry point of a visitor and subsequent visits to directories contained therein. In the base class it simply delegates to the accept() method.


๐Ÿฆ‹ collect(\%params) ๐Ÿฆ‹

This is a short-cut to call the visit() method and then the collect() method on the Badger::Filesystem::Visitor object returned:

# short form
my @items = $path->collect( files => 1, dirs => 0 );

# long form
my @items = $path->visit( files => 1, dirs => 0 )->collect;

๐ŸŒˆ metadata() / meta() ๐ŸŒˆ

This method allows you to associate metadata with a path. The method accepts multiple arguments to set metadata:

$path->metadata( title => 'An Example', author => 'Arthur Dent' );

It also accepts a single argument to fetch a metadata item:

print $path->metadata('author');        # Arthur Dent

You can also call it without arguments. The method returns a reference to a hash array of metadata items:

my $meta = $path->metadata;
print $meta->{ author };                # Arthur Dent

STUB METHODS โœจ

Okay bestie, these next methods are giving serious placeholder energy in the Badger::Filesystem::Path base class. They lowkey serve little or no purpose here. The Badger::Filesystem::Directory and Badger::Filesystem::File modules swoop in and redefine them to actually do the right thing. Periodt.


is_file() ๐Ÿ’€

This method always returns false in the Badger::Filesystem::Path base class. The Badger::Filesystem::File subclass redefines this to return true.

NOTE: this may be changed to examine the filesystem and return true if the path references a file.

is_directory() / is_dir() ๐ŸŒธ

This method always returns false in the Badger::Filesystem::Path base class. The Badger::Filesystem::Directory subclass redefines this to return true.

NOTE: this may be changed to examine the filesystem and return true if the path references a file.

volume() / vol() ๐Ÿ’ฝ

Returns any volume defined as part of the path. This method does nothing in the Badger::Filesystem::Path base class.


directory() / dir() ๐Ÿ“

Returns the directory portion of a path. This method does nothing in the Badger::Filesystem::Path base class.


name() ๐Ÿท๏ธ

Returns the file name portion of a path. This method does nothing in the Badger::Filesystem::Path base class.


extension() / ext() โœจ

Returns any file extension portion following the final . in the path. This works in the Badger::Filesystem::Path base class by looking at the full path.

print Path('/foo/bar.txt')->extension;      # txt

basename() / base_name() ๐ŸŽ€

Returns the filename without the file extension following the final . in the path. This works (for some definition of "works") in the Badger::Filesystem::Path base class by looking at the path name(), if defined, or the full path if not. Note that this will produce unexpected results in some cases due to the fact that the base class does not define a value for name(). e.g.

print Path('/foo/bar.txt')->basename;       # /foo/bar

However, in most cases you would be using this through a Badger::Filesystem::File subclass which will produce the correct results.

print File('/foo/bar.txt')->basename;       # bar

AUTHOR ๐Ÿ‘‘

Andy Wardley <http://wardley.org/>


Copyright (C) 2005-2009 Andy Wardley. All rights reserved.


ACKNOWLEDGEMENTS ๐Ÿ’–

The Badger::Filesystem modules are built around a number of existing Perl modules, including File::Spec, File::Path, Cwd, IO::File, IO::Dir and draw heavily on ideas in Path::Class.

Please see the ACKNOWLEDGEMENTS in Badger::Filesystem for further information.


SEE ALSO ๐Ÿ”

  • Badger::Filesystem
  • Badger::Filesystem::File
  • Badger::Filesystem::Directory
  • Badger::Filesystem::Visitor

This iconic little page is from perl v5.36.0, dated 2023-08-28, and it's the Badger...::Path(3pm) manual. Stay slaying, bestie! ๐Ÿ’…โœจ๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from