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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With