How can I qualify a variable as const/final in 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 $!;
...
prin开发者_StackOverflow中文版t "$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?
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";
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.
Another popular way to create read-only scalars is to modify the symbol table entry for the variable by using a typeglob:
*infilename = \"input_56_12.txt";
This only works for global variables ("my" variables have no symbol table entry).
精彩评论