[![Actions Status](https://github.com/gfx/Perl-Data-Util/workflows/test.yml/badge.svg)](https://github.com/gfx/Perl-Data-Util/actions) [![MetaCPAN Release](https://badge.fury.io/pl/Data-Util.svg)](https://metacpan.org/release/Data-Util)
# NAME

Data::Util - A selection of utilities for data and data types

# VERSION

This document describes Data::Util version 0.67

# SYNOPSIS

        use Data::Util qw(:validate);

        sub foo{
                # they will die if invalid values are supplied
                my $sref = scalar_ref(shift);
                my $aref = array_ref(shift);
                my $href = hash_ref(shift);
                my $cref = code_ref(shift);
                my $gref = glob_ref(shift);
                my $rx   = rx(shift); # regular expression
                my $obj  = instance(shift, 'Foo');
                # ...
        }

        use Data::Util qw(:check);

        sub bar{
                my $x = shift;
                if(is_scalar_ref $x){
                        # $x is an array reference
                }
                # ...
                elsif(is_instance $x, 'Foo'){
                        # $x is an instance of Foo
                }
                # ...
        }

        # miscelaneous
        use Data::Util qw(:all);

        my $x = anon_scalar();
        $x = anon_scalar($x); # OK

        my $stash = get_stash('Foo');

        install_subroutine('Foo',
                hello  => sub{ "Hello!\n" },
                goodby => sub{ "Goodby!\n" },
        );

        print Foo::hello(); # Hello!

        my($pkg, $name) = get_code_info(\&Foo::hello); # => ('Foo', 'hello')
        my $fqn         = get_code_info(\&Foo::hello); # =>  'Foo::hello'
        my $code        = get_code_ref('Foo', 'hello');  # => \&Foo::hello

        uninstall_subroutine('Foo', qw(hello goodby));

    # simple format for errro messages (not the same as Data::Dumper)
        print neat("Hello!\n"); # => "Hello!\n"
        print neat(3.14);       # => 3.14
        print neat(undef);      # => undef

# DESCRIPTION

This module provides utility functions for data and data types,
including functions for subroutines and symbol table hashes (stashes).

This module makes for a pure Perl and XS implementation. 

However, if you want to use the full capacity of it, we recommend you to opt
for the XS backend.

There are many benchmarks in the `DIST-DIR/benchmark/` directory.

# INTERFACE

## Check functions

Check functions are introduced by the `:check` import tag, which check
the argument type and return a bool.

These functions also check for overloading magic, e.g. `${}` corresponds to a SCALAR reference.

- is\_scalar\_ref(value)

    Checks for a SCALAR reference.

- is\_array\_ref(value)

    Checks for an ARRAY reference.

- is\_hash\_ref(value)

    Checks for a HASH reference.

- is\_code\_ref(value)

    Checks for a CODE reference.

- is\_glob\_ref(value)

    Checks for a GLOB reference.

- is\_rx(value)

    Checks for a regular expression reference generated by the `qr//` operator.

- is\_instance(value, class)

    Checks for an instance of _class_.

    It is equivalent to the following statement:
    `Scalar::Util::blessed($value) && $value->isa($class)`.

- is\_invocant(value)

    Checks for an invocant, i.e. a blessed reference or existent package name.

    If _value_ is a valid class name but does not exist, it will return false.

- is\_value(value)

    Checks whether _value_ is a primitive value, i.e. a defined, non-ref, and
    non-type-glob value.

    This function has no counterpart for validation.

- is\_string(value)

    Checks whether _value_ is a string with non-zero-length contents,
    equivalent to `is_value($value) && length($value) > 0`.

    This function has no counterpart for validation.

- is\_number(value)

    Checks whether _value_ is a number.
    Here, a **number** means that the perl parser can understand it and that
    the perl numeric converter (e.g. invoked by `sprintf '%g', $value`)
    doesn't complain about it.

    It is similar to `Scalar::Util::looks_like_number()`
    but refuses `infinity`, `not a number` and `"0 but true"`.
    Note that `9**9**9` makes `infinity` and `9**9**9 - 9**9**9` makes
    `not a number`.

    This function has no counterpart for validation.

- is\_integer(value)

    Checks whether _value_ is an integer.
    An **integer** is also a **number**, so this function
    refuses `infinity` and `not a number`. See also `is_number()`.

    This function has no counterpart for validation.

## Validating functions

Validating functions are introduced by the `:validate` tag which checks for
the argument and returns the first argument.
These are like the `:check` functions but dies if the argument type
is invalid.

These functions also checks overloading magic, e.g. `${}` for a SCALAR reference.

- scalar\_ref(value)

    Validates a SCALAR reference.

- array\_ref(value)

    Validates an ARRAY reference.

- hash\_ref(value)

    Validates a HASH reference.

- code\_ref(value)

    Validates a CODE reference.

- glob\_ref(value)

    Validates a GLOB reference.

- rx(value)

    Validates a regular expression reference.

- instance(value, class)

    Validates an instance of _class_.

- invocant(value)

    Validates an invocant, i.e. a blessed reference or existent package name.

    If _value_ is a valid class name and the class exists, then it returns
    the canonical class name, which is logically cleaned up. That is, it runs
    `$value =~ s/^::(?:main::)*//;` before returning it.

    NOTE:
    Canonization is done so due to an inconsistency between Perl versions. 
    For instance:

            package ::Foo; # OK
            my $x = bless {}, '::Foo'; # OK
            ref($x)->isa('Foo'); # Fatal

    The last code snippet causes a fatal error:
    `Can't call method "isa" without package or object reference`.
    However, `invocant(ref $x)->isa('Foo')` is always OK.

## Miscellaneous utilities

There are some other utility functions you can import from this module.

- anon\_scalar()

    Generates an anonymous scalar reference to `undef`.

- anon\_scalar(value)

    Generates an anonymous scalar reference to the copy of _value_.

    It is equivalent to `do{ my $tmp = $value; \$tmp; }`.

- neat(value)

    Returns a neat string that is suitable to display.

    This is a smart version of `<do{ defined($value) ? qq{"$value"} : 'undef' }`>.

- get\_stash(invocant)

    Returns the symbol table hash (also known as **stash**) of _invocant_
    if the stash exists.

- install\_subroutine(package, name => subr \[, ...\])

    Installs _subr_ into _package_ as _name_.

    It is similar to
    `do{ no strict 'refs'; *{$package.'::'.$name} = \&subr; }`.
    In addition, if _subr_ is an anonymous subroutine, it is located into
    _package_ as a named subroutine _&package::name_.

    For example:

            install_subroutine($pkg,   say => sub{ print @_, "\n" });
            install_subroutine($pkg,
                    one => \&_one,
                    two => \&_two,
            );

            # accepts a HASH reference
            install_subroutine($pkg, { say => sub{ print @_, "\n" }); #

    To re-install _subr_, use `no warnings 'redefine'` directive:

            no warnings 'redefine';
            install_subroutine($package, $name => $subr);

- uninstall\_subroutine(package, names...)

    Uninstalls _names_ from _package_.

    It is similar to `Sub::Delete::delete_sub()`, but uninstall multiple
    subroutines at a time.

    If you want to specify deleted subroutines, you can supply
    `name => \&subr` pairs.

    For example:

            uninstall_subroutine('Foo', 'hello');

            uninstall_subroutine('Foo', hello => \&Bar::hello);

            uninstall_subroutine($pkg,
                    one => \&_one,
                    two => \&_two,
            );

            # accepts a HASH reference
            uninstall_subroutine(\$pkg, { hello => \&Bar::hello });

- get\_code\_info(subr)

    Returns a pair of elements, the package name and the subroutine name of _subr_.

    It is similar to `Sub::Identify::get_code_info()`, but it returns the fully
    qualified name in scalar context.

- get\_code\_ref(package, name, flag?)

    Returns _&package::name_ if it exists, not touching the symbol in the stash.

    if _flag_ is a string `-create`, it returns _&package::name_ regardless of
    its existence. That is, it is equivalent to
    `do{ no strict 'refs'; \&{package . '::' . $name} }`.

    For example:

            $code = get_code_ref($pkg, $name);          # like  *{$pkg.'::'.$name}{CODE}
            $code = get_code_ref($pkg, $name, -create); # like \&{$pkg.'::'.$name}

- curry(subr, args and/or placeholders)

    Makes _subr_ curried and returns the curried subroutine.

    This is also considered as lightweight closures.

    See also [Data::Util::Curry](https://metacpan.org/pod/Data%3A%3AUtil%3A%3ACurry).

- modify\_subroutine(subr, ...)

    Modifies _subr_ with subroutine modifiers and returns the modified subroutine.
    This is also considered as lightweight closures.

    _subr_ must be a code reference or callable object.

    Optional arguments:
    `before => [subroutine(s)]` called before _subr_.
    `around => [subroutine(s)]` called around _subr_.
    `after  => [subroutine(s)]` called after  _subr_.

    This seems a constructor of modified subroutines and
    `subroutine_modifier()` is property accessors, but it does not bless the
    modified subroutines.

- subroutine\_modifier(subr)

    Returns whether _subr_ is a modified subroutine.

- subroutine\_modifier(modified\_subr, property)

    Gets _property_ from _modified_.

    Valid properties are: `before`, `around`, `after`.

- subroutine\_modifier(modified\_subr, modifier => \[subroutine(s)\])

    Adds subroutine _modifier_ to _modified\_subr_.

    Valid modifiers are: `before`, `around`, `after`.

- mkopt(input, moniker, require\_unique, must\_be)

    Produces an array of an array reference from _input_.

    It is compatible with `Data::OptList::mkopt()`. In addition to it,
    _must\_be_ can be a HASH reference with `name => type` pairs.

    For example:

            my $optlist = mkopt(['foo', bar => [42]], $moniker, $uniq, { bar => 'ARRAY' });
            # $optlist == [[foo => undef], [bar => [42]]

- mkopt\_hash(input, moniker, must\_be)

    Produces a hash reference from _input_.

    It is compatible with `Data::OptList::mkopt_hash()`. In addition to it,
    _must\_be_ can be a HASH reference with `name => type` pairs.

    For example:

            my $optlist = mkopt(['foo', bar => [42]], $moniker, { bar => 'ARRAY' });
            # $optlist == {foo => undef, bar => [42]}

# ENVIRONMENT VARIABLES

## DATA\_UTIL\_PUREPERL

If true, `Data::Util` uses the pure Perl implementation.

# DEPENDENCIES

Perl 5.10 or later.

If you have a C compiler, you can use the XS backend.

A pure Perl backend/implementation is also made available in case you have no C
compiler handy (unlikely!).

# BUGS AND LIMITATIONS

No bugs have been reported.

Please report any bugs or feature requests to the author.

# SEE ALSO

[Scalar::Util](https://metacpan.org/pod/Scalar%3A%3AUtil).

[overload](https://metacpan.org/pod/overload).

[Params::Util](https://metacpan.org/pod/Params%3A%3AUtil).

[Sub::Install](https://metacpan.org/pod/Sub%3A%3AInstall).

[Sub::Identify](https://metacpan.org/pod/Sub%3A%3AIdentify).

[Sub::Delete](https://metacpan.org/pod/Sub%3A%3ADelete).

[Sub::Curry](https://metacpan.org/pod/Sub%3A%3ACurry).

[Class::MOP](https://metacpan.org/pod/Class%3A%3AMOP).

[Class::Method::Modifiers](https://metacpan.org/pod/Class%3A%3AMethod%3A%3AModifiers).

[Data::OptList](https://metacpan.org/pod/Data%3A%3AOptList).

[Mouse](https://metacpan.org/pod/Mouse)

# AUTHOR

Goro Fuji(gfx) &lt;gfuji(at)cpan.org>.

# LICENSE AND COPYRIGHT

Copyright (c) 2008-2010, Goro Fuji &lt;gfuji(at)cpan.org>. All rights reserved.

This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
