good chemistry is complicated,and a little bit messy -LW PerlMonks

### Weird (?) behavior with constants under special conditions

by ceo (Acolyte)
 on Jan 31, 2013 at 14:04 UTC Need Help??
ceo has asked for the wisdom of the Perl Monks concerning the following question:

Hi everyone,
I had no chance of getting PPI installed in our environment, so I wrote a small perl-parser which does kind of okay in most cases we got here. Of course, its not as mighty as PPI, but that isnt neccessary anyway. But that isnt the topic, just somekind of bad introduction.
So, I just stumbled upon this:
You can say, let's say...
use constant g => 30;
and "print g" will print "30". Allright...
So, what if you are trying to print g divided by 5?
print (g/5)
prints 6, so, it works fine.
But what if you are going to try define another constant, named s, and try to print it, divided by 5, divided by 20, divided by g?
print (s/5/20/g)
That doesnt work. It always tries to do a substition regex on \$_, and I, of course, understand why.
But... is there no way to get the result of s divided by 5 divided by 20 divided by g, when s and g are constants? And is that really wanted?

Replies are listed 'Best First'.
Re: Weird (?) behavior with constants under special conditions
by choroba (Bishop) on Jan 31, 2013 at 14:07 UTC
Of course there is a way to get the result you want:
```print &s/5/20/g;
As you can see, it is not wise to use operator names for constants.
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
... it is not wise to use operator names for constants.

ceo: ... or for functions, which is what constants are:

```>perl -wMstrict -le
"sub tr  (&\$) { \$_[0]->(\$_[1]) }
sub trx (&\$) { \$_[0]->(\$_[1]) }
;;
\$_ = 'foo';
print 'A: ', tr{ print qq{tr match: \$_[0]} }/foo/;
print 'B: ', trx{ print qq{trx match: \$_[0]} }/foo/;
"
A: 0
trx match: 1
B: 1
Re: Weird (?) behavior with constants under special conditions
by Athanasius (Chancellor) on Jan 31, 2013 at 14:30 UTC

It might also be worth considering a switch from constant to Readonly:

``` 0:24 >perl -Mstrict -MReadonly -wE "Readonly my \$g => 30; Readonly my
+ \$s => 3000; print \$s/5/20/\$g;"
1
0:25 >

(No room for ambiguity there.)

Hope that helps,

 Athanasius <°(((>< contra mundum Iustus alius egestas vitae, eros Piratica,

Create A New User
Node Status?
node history
Node Type: perlquestion [id://1016322]
Front-paged by Corion
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2018-05-26 05:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
World peace can best be achieved by:

Results (192 votes). Check out past polls.

Notices?