Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# how to make a function lvalue?

Posted on 2001-08-02
Medium Priority
235 Views
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?
0
Question by:holli
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2
• 2

LVL 8

Expert Comment

ID: 6344633
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

LVL 8

Expert Comment

ID: 6344662
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

LVL 6

Author Comment

ID: 6346171
0

LVL 6

Author Comment

ID: 6346176
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

Accepted Solution

zhire earned 300 total points
ID: 6348000
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

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…