in reply to Method for reducing tedium of transferring object properties to scalars
In your simple case of printing several values with a constant separator, there's either join, or $,:
All three of those solutions have their downside though.print "Values: ", join ", ", $self->get_value1, $self->get_value2, $se +lf->get_value3"; print "\nValues: "; { local $, = ", "; print $self->get_value1, $self->get_value2, $self->get_value3"; print "\nValues: ".$self->get_value1, $self->get_value2, $self->get_ +value3"; # notice the . after "\nValues: " }
For the most general case of printing method calls inside double quotes, all I can think of is using a tied hash to call the methods when accessing it. It works but it kind of defeats the purpose of writing accessor methods in the first place:
use v5.14; use strict; use warnings; package Test { sub new { my $scalar = $_[1]; bless \$scalar, shift } sub value { ${ $_[0] } = $_[1] if @_ > 1; ${ $_[0] } } } package CallerHash { sub TIEHASH { return bless \$_[1], $_[0]; } sub FETCH { my $obj = ${ +shift }; my $method = shift; return $obj->$method(); } sub STORE { my $obj = ${ +shift }; my $method = shift; $obj->$method(@_); } } my $obj = Test->new(4); tie my %objAsHash, CallerHash => $obj; say "$objAsHash{value}"; $objAsHash{value} = 42; say "$objAsHash{value}"; say $$obj;
Edit: BTW, the fact that $method = "method_name"; $obj->$method(); works even under strict might help you come up with another solution to print the output of method calls without concatenating bits of strings. Maybe something like: print replace $self, "Values: {self:get_value1}, {self:get_value2}, {self:get_value3}"; where replace uses s///ge;
(so now that I think of it, the tied hash isn't the only solution I can come up with)
Edit2: haukex is right. Using a templating engine is probably the best idea
|
|---|