checking if value is lvalue(modifiable) or not

Y

Yakov

Is there a function that tests whether $_[0] is bound to modifiable
variable (like in foo($var)) or to non-modifiable variable (like in
foo("str")) ?

The context of my question is like this:
sub chompit { # chomp + returns the result + modify the arg if
possible
if(modifiable($_[0])) {
# is there any modifiable() function ?
chomp($_[0]);
return $_[0];
} else {
# we can't apply chomp() to the arg, it's constant
my ($copy) = shift;
chomp($copy);
return $copy;
}
}
$result = chompit(`date`); #arg is constant
$result = chompit($_); # arg is not constant

Thanks
Yakov
 
A

anno4000

Yakov said:
Is there a function that tests whether $_[0] is bound to modifiable
variable (like in foo($var)) or to non-modifiable variable (like in
foo("str")) ?

see readonly() in Scalar::Util

[snip]

Anno
 
B

Brian McCauley

$result = chompit(`date`); #arg is constant

Actually, qx// (like most Perl builtin functions and normal
(non-lvalue) subroutines) doesn't return a readonly values.

You'd think that you could force a subroutine to return a readonly
value by using an lvalue subroutine but actually Perl will, in effect,
dynamically undo the lvalue-ness of the subroutine if you try.

sub foo : lvalue {
my $x = \my $y; # $x is ref to variable
print 'In foo $x is ',$x;
$$x;
}

print ' \foo is ',\foo,"\n";

sub bar : lvalue {
my $x = \1; # $x is ref to constant
print 'In bar $x is ',$x;
$$x;
}

print ' \bar is ',\bar,"\n";
 
Y

Yakov

Brian said:
Actually, qx// (like most Perl builtin functions and normal
(non-lvalue) subroutines) doesn't return a readonly values.

But then, why do I get following error trying to modify `xxx`:

perl -e 'chomp(`date`)'
Can't modify quoted execution (``, qx) in chomp at -e line 1, at end
of line
Execution of -e aborted due to compilation errors.

Yakov
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top