use constant behavior

C

ccc31807

use constant DIR => 'log_files';
mkdir DIR unless -e DIR;

This places a subdirectory in my current working directory named
log_files, creating it if it doesn't exist.

print_log();
sub print_log
{
open LOG, '>', "DIR/log.csv" or die "Cannot open LOG, $!";
...
}

This throws a DOES NOT EXIST error. However,

print_log(DIR);
sub print_log
{
my $dir = shift;
open LOG, '>', "$dir/log.csv" or die "Cannot open LOG, $!";
...
}

works just fine. What am I missing?

Thanks, CC.
 
U

Uri Guttman

c> use constant DIR => 'log_files';
c> mkdir DIR unless -e DIR;

c> This places a subdirectory in my current working directory named
c> log_files, creating it if it doesn't exist.

c> print_log();
c> sub print_log
c> {
c> open LOG, '>', "DIR/log.csv" or die "Cannot open LOG, $!";
c> ...
c> }

c> This throws a DOES NOT EXIST error. However,

perl constants are really subs with a prototype of no arguments. they
are converted at compile to their value (and constant folded if
possible).

"DIR" won't work because subs don't directly interpolate. you can work
around that with DIR . '/log.csv' or the @{[DIR]} interpolation trick.

another way is to use the ReadOnly module which declares regular
variables which can't be modified. then you can use $DIR in either situation.

uri
 
C

ccc31807

perl constants are really subs with a prototype of no arguments. they
are converted at compile to their value (and constant folded if
possible).

Uri, thanks for your explanation.

I would then assume that
- use constant DIR => 'log_files';
would be more or less equivalent to
- sub DIR { return 'log_files'; }

Is this assumption correct, more or less?

Thanks, CC.
 
U

Uri Guttman

c> Uri, thanks for your explanation.

c> I would then assume that
c> - use constant DIR => 'log_files';
c> would be more or less equivalent to
c> - sub DIR { return 'log_files'; }

sub DIR() { 'log_files' }

the important difference is the prototype of () so it can be compile
time converted to a constant. the return isn't needed (i dunno if it
affects it becoming a proper constant but i doubt it).

uri
 
C

ccc31807

    ~/src/perl/perl% perl -MO=Concise -e'sub FOO(){"bar"} FOO'

Ben,

I assume that -MO means to use the O module that provides a generic
interface to Perl Compiler backends, and that =Concise avoids verbose
output. Where would I find the documentation on the options for O and
a description of the output?

Thanks, CC.
 

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
474,215
Messages
2,571,113
Members
47,708
Latest member
SharonMaes

Latest Threads

Top