That's a little more efficient than the solution I came up with, give thx!
foreach my $o (%{$c})
{
if(ref(\$o) eq 'REF' && exists($o->{Device}) && $o->{Device} eq $dev
+ice)
{
$o->motion;
last;
}
}
| [reply] [d/l] |
If you are just going to literally iterate over the structure of your object, you really should be doing some checking to ensure each value is an object you can act upon. Personally, if I were to do something like this, I'd make a sensors top-level key, and stuff the sensors in there. That way, all sensor objects are within a single location. This allows greater flexibility going forward.
Either way, UNIVERSAL::can is a decent, clean way to see if a) the value of each key is indeed an object, and b) checks whether it can perform a specific task:
use warnings;
use strict;
package Device; {
sub new {
my $self = bless {}, shift;
$self->{s1} = Sensor->new;
$self->{s2} = Sensor->new;
$self->{s3} = "string";
return $self;
}
sub event {
my ($self) = @_;
for (keys %{ $self }){
if (UNIVERSAL::can($self->{$_}, 'motion')){
print "yep, '$_' is a sensor object\n";
}
else {
print "'$_' isn't a damned sensor!\n";
}
}
}
}
package Sensor; {
sub new {
return bless {}, shift;
}
sub motion {
...
}
}
package main;
my $device = Device->new;
$device->event;
Output:
yep, 's1' is a sensor object
's3' isn't a damned sensor!
yep, 's2' is a sensor object
| [reply] [d/l] [select] |