Link to home
Start Free TrialLog in
Avatar of holli
holli

asked on

how to make a function lvalue?

hi experts.

some functions in perl can be lvalue. eg. substr.

$foo=substr($bar,1,2); #rvalue
substr($bar,1,2)=$foo; #lvalue

how can i mimic this behaviour in a self-written perl-function?
Avatar of bebonham
bebonham

basically you use the modifier lvalue


something like


@arr=qw/one two three four/;

sub ref : lvalue
{
$pt=shift;
for($i=0;$i<4;$i++)
{
if($pt->[$i]=="three")
{
$po=$i;
}}
$pt->[$po];

}
print $arr[3];
ref(\@arr)="eighteen";
print $arr[3];

sorry, that was about the worst example I could ever give...

try this:



@arr=qw/one two three four/;

sub ref2 : lvalue
{
$pt=shift;
for($i=0;$i<scalar @$pt;$i++)
{
if($pt->[$i]=~/three/)
{
$po=$i;
}}
$pt->[$po];
}
print $arr[2] . "\n";
ref2(\@arr)="eighteen";
print $arr[2];
Avatar of holli

ASKER

Avatar of holli

ASKER

so i need a global variable?
that's bad. i wanted to implement something like this:

package foo;

sub new { return bless ( {}, shift ); }

sub property : lvalue
{ my $this=shift; my $prop=shift;

  $this->{$prop}=lvalue if lvalue;
  return $this->$prop

}  

1;

----

use foo;

my $f=foo->new();
$f->property("color")="red";
print $f->property("color"); #->red


is there a way to do that?
ASKER CERTIFIED SOLUTION
Avatar of zhire
zhire

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial