Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: Moose: using value of one attribute in another attribute

by tobyink (Abbot)
on Jan 11, 2013 at 23:39 UTC ( #1012996=note: print w/replies, xml ) Need Help??

in reply to Moose: using value of one attribute in another attribute

You seem to be hard-coding information about a specific battery into the battery class.

That would be like if I was trying to create a class to represent people, hard-coding my personal details as the defaults.

use 5.010; { package Acpi::Info; use Moose; my @attrs = qw< name type online status present technology voltage_min_design voltage_now current_now charge_full_design charge_full charge_now model_name manufacturer serial_number >; for my $attr (@attrs) { has $attr => ( is => "ro", lazy => 1, default => sub { my $self = shift; $self->_build($attr) } ); } sub _build { my ($self, $key) = @_; my $data = $self->_data; $key = "POWER_SUPPLY_" . uc($key); $data =~ /^$key=(.+?)$/m and $1; } has file => ( is => "ro", isa => "Str", ); has _data => ( is => "ro", isa => "Str", lazy => 1, builder => '_build_data', ); sub _build_data { my $self = shift; local @ARGV = $self->file; local $/ = <ARGV>; } } # Usage # my $i1 = Acpi::Info->new(file => '/sys/class/power_supply/BAT1/uevent' +); my $i2 = Acpi::Info->new(file => '/sys/class/power_supply/ACAD/uevent' +); for my $supply ($i1, $i2) { say "----"; for my $attr ($supply->meta->get_all_attributes) { my $aname = $attr->name; next if $aname =~ /^_/; say $aname, " = ", $supply->$aname; } }
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^2: Moose: using value of one attribute in another attribute
by mimosinnet (Beadle) on Jan 12, 2013 at 10:57 UTC

    Thanks very much for you clear and detailed answer! A good insight on how objects work! It is also very enlightening to understand your example on how to read the contents of the file. Also, I was not aware of the use of the underscore to make attributes and builders private!

      Perl doesn't have true private methods. Underscores are merely a convention to indicate that a sub is intended for internal use only.

      It is possible to create do-it-yourself private subs by checking caller within a sub and then calling die if the caller is outside your module. Though this will have a performance impact if you do it a lot, and is of questionable benefit.

      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

        A simpler alternative to caller would be:

        my $private = sub { ... };

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1012996]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2018-05-20 14:56 GMT
Find Nodes?
    Voting Booth?