in reply to Method for reducing tedium of transferring object properties to scalars
Note that, because this accesses the underlying data without using any accessors, then you may get incorrect results if your accessors do anything more than just forward the underlying data to the caller (e.g., calculated properties).#!/usr/bin/env perl use strict; use warnings; use 5.010; package Foo; sub new { return bless $_[1] } sub show_properties { my $self = shift; my ($foo, $bar, $baz) = @$self{qw( foo bar baz )}; say "foo: $foo, bar: $bar, baz: $baz"; } package main; my $foo = Foo->new( { foo => 1, bar => 2, baz => 3 } ); $foo->show_properties;
Generally speaking, you can also do this to suck property values out of other objects[1], but that's a blatant violation of encapsulation and ties you directly to the internal implementation of the other class, so it's probably not a particularly good idea. (Doing this with $self similarly ties you to the internal implementation as well, of course, but, since it's within the same class, I don't consider it that big a deal. Others disagree quite strongly, and will maintain that accessors should always be used, without exception, even within the same class.)
[1] ...because almost all objects in Perl are blessed hashrefs and because "Perl doesn't have an infatuation with enforced privacy. It would prefer that you stayed out of its living room because you weren't invited, not because it has a shotgun."
|
|---|