Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to conditionally pass options to a method in perl?

Tags:

methods

perl

Similar to this question regarding Ruby, I'd like to conditionally pass parameters to a method. Currently, I have it configured as follows:

my $recs = $harvester->listAllRecords(
    metadataPrefix => 'marc21',
    metadataHandler => 'MARC::File::SAX',
    set => 'pd',
    from => $from,
    until => $until,
);

What I'd like is to be able to conditionally pass the from and/or until parameters, depending on previous code. This is not syntactically correct, but something like this:

from => $from if ($from),
until => $until if ($until),

or this:

if ($from) {from => $from,}
if ($until) {until => $until,}

Is this possible, and if so, how would I go about doing it?

like image 739
ND Geek Avatar asked Jan 17 '13 18:01

ND Geek


2 Answers

You could use the ternary ?: operator with list operands:

my $recs = $harvester->listAllRecords(
    metadataPrefix => 'marc21',
    metadataHandler => 'MARC::File::SAX',
    set => 'pd',

    $from ? (from => $from) : (),
    $until ? (until => $until) : (),
);

It may also be worth knowing about the "conditional list include" pseudo-operator, which in this case would work like

...
(from => $from) x !!$from,
(until => $until) x !!defined($until),
...

but the ternary operator expression is probably easier to read for most people.

like image 129
mob Avatar answered Nov 04 '22 16:11

mob


The other option is to build a list (or hash) of args and then call the method:

my %args = (
    metadataPrefix => 'marc21',
    metadataHandler => 'MARC::File::SAX',
    set => 'pd',
);
$args{from} = $from if $from;
$args{until} = $until if $until;

my $recs = $harvester->listAllRecords(%args);
like image 38
Ryan C. Thompson Avatar answered Nov 04 '22 18:11

Ryan C. Thompson