---
name: "Catmandu::Util"
section: "3pm"
platform: "linux"
package: "libcatmandu-perl"
version: "1.2024-1"
release: "Debian 13 (Trixie)"
platforms: ["linux"]
url: "https://new.carta.tech/Catmandu::Util"
---

# Catmandu::Util(3pm)

A collection of utility functions

## NAME

Catmandu::Util - A collection of utility functions

## SYNOPSIS

```
    use Catmandu::Util qw(:string);
    $str = trim($str);
```

## FUNCTIONS

### IO functions

```
    use Catmandu::Util qw(:io);
```

- io($io, %opts)

  Takes a file path, glob, glob reference, scalar reference or IO::Handle object and returns an opened IO::Handle object.

  ```
      my $fh = io '/path/to/file';
      my $fh = io *STDIN;
      my $fh = io \*STDOUT, mode => 'w', binmode => ':crlf';
      my $write_cb = sub { my $str = $_[0]; ... };
      my $fh = io $write_cb, mode => 'w';
      my $scalar = "";
      my $fh = io \$scalar, mode => 'w';
      $fh->print("some text");
  ```

  Options are:

  - mode

    Default is `"r"`.

  - binmode

    Default is `":encoding(UTF-8)"`.

  - encoding

    Alias for `"binmode"`.

- read\_file($path);

  \[deprecated\]: use tools like Path::Tiny instead.

  Reads the file at `$path` into a string.

  ```
      my $str = read_file('/path/to/file.txt');
  ```

  Throws a Catmandu::Error on failure.

- read\_io($io)

  Reads an IO::Handle into a string.

  ```
     my $str = read_file($fh);
  ```

- write\_file($path, $str);

  \[deprecated\]: use tools like use tools like File::Slurp::Tiny instead.

  Writes the string `$str` to a file at `$path`.

  ```
      write_file('/path/to/file.txt', "contents");
  ```

  Throws a Catmandu::Error on failure.

- read\_yaml($path);

  Reads the YAML file at `$path` into a Perl hash.

  ```
      my $cfg = read_yaml($path);
  ```

  Dies on failure reading the file or parsing the YAML.

- read\_json($path);

  Reads the JSON file at `$path` into a Perl hash.

  ```
      my $cfg = read_json($path);
  ```

  Dies on failure reading the file or parsing the JSON.

- join\_path(@path);

  Joins relative paths into an absolute path.

  ```
      join_path('/path/..', './to', 'file.txt');
      # => "/to/file.txt"
  ```

- normalize\_path($path);

  Normalizes a relative path to an absolute path.

  ```
      normalize_path('/path/../to/./file.txt');
      # => "/to/file.txt"
  ```

- segmented\_path($path);

  ```
      my $id = "FB41144C-F0ED-11E1-A9DE-61C894A0A6B4";
      segmented_path($id, segment_size => 4);
      # => "FB41/144C/F0ED/11E1/A9DE/61C8/94A0/A6B4"
      segmented_path($id, segment_size => 2, base_path => "/files");
      # => "/files/FB/41/14/4C/F0/ED/11/E1/A9/DE/61/C8/94/A0/A6/B4"
  ```

- content\_type($filename);

  Guess the content type of a file name.

  ```
      content_type("book.pdf");
      # => "application/pdf"
  ```

### Hash functions

```
    use Catmandu::Util qw(:hash);
```

A collection of functions that operate on hash references.

- hash\_merge($hash1, $hash2, ... , $hashN)

  Merge \<hash1\> through \<hashN\>,  with the nth-most (rightmost) hash taking precedence. Returns a new hash reference representing the merge.

  ```
      hash_merge({a => 1}, {b => 2}, {a => 3});
      # => { a => 3 , b => 2}
  ```

### Array functions

```
    use Catmandu::Util qw(:array);
```

A collection of functions that operate on array references.

- array\_exists($array, $index)

  Returns `1` if `$index` is in the bounds of `$array`

  ```
      array_exists(["a", "b"], 2);
      # => 0
      array_exists(["a", "b"], 1);
      # => 1
  ```

- array\_group\_by($array, $key)

  ```
      my $list = [{color => 'black', id => 1},
                  {color => 'white', id => 2},
                  {id => 3},
                  {color => 'black', id => 4}];
      array_group_by($list, 'color');
      # => {black => [{color => 'black', id => 1}, {color => 'black', id => 4}],
      #     white => [{color => 'white', id => 2}]}
  ```

- array\_pluck($array, $key)

  ```
      my $list = [{id => 1}, {}, {id => 3}];
      array_pluck($list, 'id');
      # => [1, undef, 3]
  ```

- array\_to\_sentence($array)

  - array\_to\_sentence($array, $join)

  - array\_to\_sentence($array, $join, $join\_last)

  ```
      array_to_sentence([1,2,3]);
      # => "1, 2 and 3"
      array_to_sentence([1,2,3], ",");
      # => "1,2 and 3"
      array_to_sentence([1,2,3], ",", " & ");
      # => "1,2 & 3"
  ```

- array\_sum($array)

  ```
      array_sum([1,2,3]);
      # => 6
  ```

- array\_includes($array, $val)

  Returns 1 if `$array` includes a value that is deeply equal to `$val`, 0 otherwise. Comparison is done with `is_same()`.

  ```
      array_includes([{color => 'black'}], {color => 'white'});
      # => 0
      array_includes([{color => 'black'}], {color => 'black'});
      # => 1
  ```

- array\_any($array, \\&sub)

  ```
      array_any(["green", "blue"], sub { my $color = $_[0]; $color eq "blue" });
      # => 1
  ```

- array\_rest($array)

  Returns a copy of `$array` without the head.

  ```
      array_rest([1,2,3,4]);
      # => [2,3,4]
      array_rest([1]);
      # => []
  ```

- array\_uniq($array)

  Returns a copy of `$array` with all duplicates removed.

- array\_split($array \| $string)

  Returns `$array` or a new array by splitting `$string` at commas.

### String functions

```
    use Catmandu::Util qw(:string);
```

- as\_utf8($str)

  Returns a copy of `$str` flagged as UTF-8.

- trim($str)

  Returns a copy of `$str` with leading and trailing whitespace removed.

- capitalize($str)

  Equivalent to `"ucfirst lc as_utf8 $str"`.

### Is functions

```
    use Catmandu::Util qw(:is);
    is_number(42) ? "it's numeric" : "it's not numeric";
    is_maybe_hash_ref({});
    # => 1
    is_maybe_hash_ref(undef);
    # => 1
    is_maybe_hash_ref([]);
    # => 0
```

A collection of predicate functions that test the type or value of argument `$val`.  Each function (except `is_same()` and `"is_different"`) also has a *maybe* variant that also tests true if `$val` is undefined. Returns `1` or `0`.

- is\_invocant($val)

  - is\_maybe\_invocant($val)

  Tests if `$val` is callable (is an existing package or blessed object).

- is\_able($val, @method\_names)

  - is\_maybe\_able($val, @method\_names)

  Tests if `$val` is callable and has all methods in `@method_names`.

- is\_instance($val, @class\_names)

  - is\_maybe\_instance($val, @class\_names)

  Tests if `$val` is a blessed object and an instance of all the classes in `@class_names`.

- is\_ref($val)

  - is\_maybe\_ref($val)

  Tests if `$val` is a reference. Equivalent to `"ref $val ? 1 : 0"`.

- is\_scalar\_ref($val)

  - is\_maybe\_scalar\_ref($val)

  Tests if `$val` is a scalar reference.

- is\_array\_ref($val)

  - is\_maybe\_array\_ref($val)

  Tests if `$val` is an array reference.

- is\_hash\_ref($val)

  - is\_maybe\_hash\_ref($val)

  Tests if `$val` is a hash reference.

- is\_code\_ref($val)

  - is\_maybe\_code\_ref($val)

  Tests if `$val` is a subroutine reference.

- is\_regex\_ref($val)

  - is\_maybe\_regex\_ref($val)

  Tests if `$val` is a regular expression reference generated by the `"qr//"` operator.

- is\_glob\_ref($val)

  - is\_maybe\_glob\_ref($val)

  Tests if `$val` is a glob reference.

- is\_value($val)

  - is\_maybe\_value($val)

  Tests if `$val` is a real value (defined, not a reference and not a glob.

- is\_string($val)

  - is\_maybe\_string($val)

  Tests if `$val` is a non-empty string. Equivalent to `"is_value($val) && length($val) > 0"`.

- is\_number($val)

  - is\_maybe\_number($val)

  Tests if `$val` is a number.

- is\_integer($val)

  - is\_maybe\_integer($val)

  Tests if `$val` is an integer.

- is\_natural($val)

  - is\_maybe\_natural($val)

  Tests if `$val` is a non-negative integer. Equivalent to `"is_integer($val) && $val >= 0"`.

- is\_positive($val)

  - is\_maybe\_positive($val)

  Tests if `$val` is a positive integer. Equivalent to `"is_integer($val) && $val >= 1"`.

- is\_float($val)

  - is\_maybe\_float($val)

  Tests if `$val` is a floating point number.

- is\_same($val, $other\_val)

  Tests if `$val` is deeply equal to `$other_val`.

- is\_different($val, $other\_val)

  The opposite of `is_same()`.

### Check functions

```
    use Catmandu::Util qw(:check);
    check_hash_ref({color => 'red'});
    # => {color => 'red'}
    check_hash_ref([]);
    # dies
```

A group of assert functions similar to the `":is"` group, but instead of returning true or false they return their argument or die.

- check\_invocant($val)

  - check\_maybe\_invocant($val)

  - check\_able($val, @method\_names)

  - check\_maybe\_able($val, @method\_names)

  - check\_instance($val, @class\_names)

  - check\_maybe\_instance($val, @class\_names)

  - check\_ref($val)

  - check\_maybe\_ref($val)

  - check\_scalar\_ref($val)

  - check\_maybe\_scalar\_ref($val)

  - check\_array\_ref($val)

  - check\_maybe\_array\_ref($val)

  - check\_hash\_ref($val)

  - check\_maybe\_hash\_ref($val)

  - check\_code\_ref($val)

  - check\_maybe\_code\_ref($val)

  - check\_regex\_ref($val)

  - check\_maybe\_regex\_ref($val)

  - check\_glob\_ref($val)

  - check\_maybe\_glob\_ref($val)

  - check\_value($val)

  - check\_maybe\_value($val)

  - check\_string($val)

  - check\_maybe\_string($val)

  - check\_number($val)

  - check\_maybe\_number($val)

  - check\_integer($val)

  - check\_maybe\_integer($val)

  - check\_natural($val)

  - check\_maybe\_natural($val)

  - check\_positive($val)

  - check\_maybe\_positive($val)

  - check\_float($val)

  - check\_maybe\_float($val)

  - check\_same($val, $other\_val)

  - check\_different($val, $other\_val)

  ### Human output functions

```
    use Catmandu::Util qw(:human);
```

- human\_number($num)

  Insert a comma a 3-digit intervals to make `$num` more readable. Only works with *integers* for now.

  ```
      human_number(64354);
      # => "64,354"
  ```

- human\_byte\_size($size)

  ```
      human_byte_size(64);
      # => "64 bytes"
      human_byte_size(10005000);
      # => "10.01 MB"
  ```

- human\_content\_type($content\_type)

  - human\_content\_type($content\_type, $default)

  ```
      human_content_type('application/x-dos_ms_excel');
      # => "Excel"
      human_content_type('application/zip');
      # => "ZIP archive"
      human_content_type('foo/x-unknown');
      # => "foo/x-unknown"
      human_content_type('foo/x-unknown', 'Unknown');
      # => "Unknown"
  ```

### XML functions

```
    use Catmandu::Util qw(:xml);
```

- **xml\_declaration()**

  Returns `"qq(<?xml version="1.0" encoding="UTF-8"?>\n)"`.

- xml\_escape($str)

  Returns an XML escaped copy of `$str`.

### Miscellaneous functions

- require\_package($pkg)

  - require\_package($pkg, $namespace)

  Load package `$pkg` at runtime with `"require"` and return it's full name.

  ```
      my $pkg = require_package('File::Spec');
      my $dir = $pkg->tmpdir();
      require_package('Util', 'Catmandu');
      # => "Catmandu::Util"
      require_package('Catmandu::Util', 'Catmandu');
      # => "Catmandu::Util"
  ```

  Throws a Catmandu::Error on failure.

- use\_lib(@dirs)

  Add directories to `@INC` at runtime.

  Throws a Catmandu::Error on failure.

- pod\_section($package\_or\_file, $section \[, @options\] )

  Get documentation of a package for a selected section. Additional options are passed to Pod::Usage.

- now($format)

  Returns the current datetime as a string. `$format`can be any `"strftime"` format. There are also 2 builtin formats, `"iso_date_time"` and `"iso_date_time_millis"`.  `"iso_date_time"` is equivalent to `"%Y-%m-%dT%H:%M:%SZ"`. `"iso_date_time_millis"` is the same, but with added milliseconds.

  ```
      now('%Y/%m/%d');
      now('iso_date_time_millis');
  ```

  The default format is `"iso_date_time"`;
