Kwargs

 view release on metacpan or  search on metacpan

lib/Kwargs.pm  view on Meta::CPAN

package Kwargs;

# ABSTRACT: Simple, clean handing of named/keyword arguments.

use strict;
use warnings;

use Sub::Exporter -setup => {
    exports => [ qw(kw kwn) ],
    groups  => {
        default => [ qw(kw kwn) ],
    }
};

sub kwn(\@@) {
    my $array = shift;
    my $npos  = shift;
    my @pos   = splice(@$array, 0, $npos) if $npos > 0;
    my $hash  = @$array == 1 ? $array->[0] : { @$array };
    return (@pos, $hash) unless @_;
    return (@pos, @{$hash}{@_});
}

sub kw(\@@) {
    splice(@_, 1, 0, 0);
    goto &kwn;
}

1;



=pod

=head1 NAME

Kwargs - Simple, clean handing of named/keyword arguments.

=head1 VERSION

version 0.01

=head1 SYNOPSIS

    use Kwargs;

    # just named
    my ($foo, $bar, baz) = kw @_, qw(foo bar baz);

    # positional followed by named
    my ($pos, $opt_one, $opt_two) = kwn @_, 1, qw(opt_one opt_two)

    # just a hashref
    my $opts = kw @_;

    # positional then hashref
    my ($one, $two, $opts) = kwn @_, 2;

=head1 WHY?

Named arguments are good, especially when you take lots of (sometimes
optional) arguments. There are two styles of passing named arguments (by
convention) in perl though, with and without braces:

    sub foo {
        my $args = shift;
        my $bar  = $args->{bar};
    }

    foo({ bar => 'baz' });

    sub bar {
        my %args = @_;
        my $foo  = $args{foo};
    }

    bar(foo => 'baz');

If you want to support both calling styles (because it should be mainly a
style issue), then you have to do something like this:

    sub foo {
        my $args = ref $_[0] eq 'HASH' ? $_[0] : { @_ };
        my $bar  = $args->{bar};



( run in 2.133 seconds using v1.01-cache-2.11-cpan-ad19def0cd9 )