On Tue, Jul 28, 2009 at 17:05, Dermot<[email protected]> wrote:
snip
>> my $bid = shift;
>> my $items = ref $_[0] ? $_[0] : \...@_;
>>
>
> Perhaps you can expand, if $_[0] was a scalar wouldn't that get
> assigned to $items?
snip
Normal scalars (i.e. strings and numbers) are not references,
therefore the result of the ref call will be undef and \...@_ will be
used. If $_[0] is a reference it will be used.
snip
> I venture this but only because I suspect I am missing something in
> your example:
> my $items = ( ref($_[0]) eq 'ARRAY' ) ? $_[0] : \...@_;
snip
Never say ref($foo) eq 'ARRAY', it is extraordinarily dangerous. If
$foo is a blessed array ref you will get back the class it has been
blessed into rather than 'ARRAY'. It is safe to use ref to find out
two things: if a scalar is a reference and the class of an object.
Use the reftype function from [Scalar::Util][1] if you want to know
what type of variable a reference points to.
For maximum safety, you should write the code like this
use Carp;
use Scalar::Util qw/reftype/;
.
.
.
sub addItemsToBasket {
croak "bad number of arguments" unless @_ == 2;
my ($bid, $items) = @_;
#code to check that $bid is a valid value, croak if it isn't
$items = [$items] unless ref $items;
croak "ITEMS should be an arrayref or a simple scalar"
unless reftype $items eq "ARRAY";
for my $item (@$items) {
unless (SOME CHECK TO MAKE SURE ITEM IS VALID) {
carp "item $item is not valid";
next;
}
#do stuff with $item
}
}
[1] : http://perldoc.perl.org/Scalar/Util.html
--
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/