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

In reply to Re^3: Loop though class attributes by stevieb
in thread Loop though class attributes by ZX81Meister

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.