# 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?
LVL 6
Asked:
###### Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
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];

0
Commented:
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];
0
Author Commented:
0
Author Commented:
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?
0
Commented:
package PropTest;

sub new { bless {},shift; }
sub property : lvalue {
my(\$self,\$prop) = @_;

# lvalue subroutines must return existing thing.
# so we use reference trick.
\${\\$self->{\$prop}};
}

1;

----

use PropTest;

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

----

This sample works properly.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Perl

From novice to tech pro — start learning today.