Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I qualify a variable as const/final in Perl?

Tags:

constants

perl

For example, in situations like below, I do not want to change the value of $infilename anywhere in the program after initialization.

my $infilename = "input_56_12.txt";
open my $fpin, '<', $infilename
    or die $!;

...
print "$infilename has $result matches\n";

close $fpin;

What is the correct way to make sure that any change in $infilename results in not just warnings, but errors?

like image 437
Lazer Avatar asked Nov 03 '10 18:11

Lazer


2 Answers

use Readonly;
Readonly my $infilename => "input_56_12.txt";

Or using the newer Const::Fast module:

use Const::Fast;
const my $infilename => "input_56_12.txt";
like image 96
Eugene Yarmash Avatar answered Sep 20 '22 17:09

Eugene Yarmash


use constant INPUT_FILE => "input_56_12.txt";

Might be what you want. If you need to initialize it to something that may change at run time then you might be out of luck, I don't know if Perl supports that.

EDIT: Oh, look at eugene y's answer, Perl does support that.

like image 33
Peter C Avatar answered Sep 23 '22 17:09

Peter C