Home

Search this site:
 

Horshack’s
very
own site

 

This is Bavaria, Germany!
You will find links to Perl,
bootdisks for system administration,
a lot of Linux,
Windows administration
and some personal belongings.
Check Parameters with Params::Validate

Check Parameters with Params::Validate

Check arguments in hashref

#!/usr/bin/perl
use strict;
use warnings;
use Params::Validate qw(:all);

lift_it( {} );
lift_it( { item => 'car' } );
lift_it( { item => 'girly', how_often => 12 } );


=head2 lift_it

Usage:

    lift_it( { } );
    lift_it( { item => 'car', how_often => 3 } );
    lift_it( { item => 'girly', how_often => 12 } );

=cut

sub lift_it {
    my $args_href = shift;

    %$args_href = validate_with(
        params => $args_href,
        spec => {
            item => {
                type => SCALAR,
                optional => 1,
                default => 'pencil',
            },
            how_often => {
                type => SCALAR,
                optional => 1,
                default => 3,
            },
        }
    );

    printf "I shall lift a %s %d times.\n",
        $args_href->{item},
        $args_href->{how_often};

}

Check arguments in subroutine in a module

#!/usr/bin/perl
use strict;
use warnings;

my $gym = Gym->new();
$gym->lift_it( {} );
$gym->lift_it( { item => 'car' } );
$gym->lift_it( { item => 'girly', how_often => 12 } );


package Gym;
use strict;
use warnings;
use Params::Validate qw(:all);

sub new {
    my $class = shift;
    my $self = bless {}, $class;
    return $self;
}

=head2 lift_it

Usage:

    # Defaults only:
    $a_gym->lift_it( );
    # Tell exactly what to do
    $a_gym->lift_it( { item => 'car', how_often => 3 } );

=cut

sub lift_it {
    # call me with: object, { hashref => .. } as arguments
    my ($self, $args_href) = validate_pos(
        @_,
        { type => OBJECT },
        { type => HASHREF, optional => 1, default => {} },
    );

    # check hashref more detailed
    %$args_href = validate_with(
        params => $args_href,
        spec => {
            item => {
                type => SCALAR,
                optional => 1,
                default => 'pencil',
            },
            how_often => {
                type => SCALAR,
                optional => 1,
                default => 3,
            },
        }
    );

    printf "I shall lift a %s %d times.\n",
        $args_href->{item},
        $args_href->{how_often};

}

Impressum