prototypes

A

ace

I would like to make a prototype for hpush subroutine which then can be
used like:

hpush %hash, %h2;
hpush %hash, {foo => 1};


Currently I have to dereference the hash which looks quite ugly:

hpush %hash, %{{foo => 1}};


=============
sub hpush(\%\%) {
my ($h1, $h2) = @_;
%$h1 = (%$h1, %$h2);
return $h2;
}
 
S

sreservoir

Ben said:
You can't do that with prototypes.


The best answer here is

sub hpush (\%%) {
my ($h1, %h2) = @_;
%$h1 = (%$h1, %$h2);
return scalar keys %$h1;
}

Note that a % in the prototype will still allow odd-numbered arguments.
 
S

sreservoir

Ben said:
Yes. % in a prototype is in every way equivalent to @.

The assignment will give a warning, and that can trivially be replaced
with a (more helpful) error with

sub hpush (\%%) {
@_ % 2 or croak "Odd number of elements in hpush";

that croak should be:
@_ % 2 and croak ...

@_ % 2 == 1 if @_ is odd, 0 if even.

In general trying to to compile-time argument checking is futile in Perl
5: the language is just too dynamic. Perl 6 is making a serious attempt
to fix that, at least where it's useful to do so.

Yet another reason for perl6!
 
S

sreservoir

Ben said:
No it shouldn't.


Yes...

(think about it more carefully :))

Oh, yes, the \%. I was giving bad advice for a while yesterday. Maybe I
need to sleep more. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top