I write the perl script, and I assigned $k="bag". I write $k===1234 inside a text file, then use perl to read the file and save it in hash. But the output I get is like '$k' => '1234', but I wish to get 'bag' =>'1234'.
The contents in text file will automatically save as string? or word? but I want it in a variable. Because there are many pairs that are needed to save in a file? and needed to updated if have the new pair. Is it possible to do it in file? or what is the way I can do?
CodePudding user response:
When you read a file in Perl, you'll get the contents of the file. Perl will not interpret the contents of the file as code and will not replace variables.
Instead, you will have to replace the variables in there yourself – essentially, you would be creating your own template language. If you only want to replace scalar variables this is typically fairly easy. The core idea is that you have to create a hash containing the variables (e.g. my %variables = (k => "bag")
and then run a regex over your file contents to replace occurrences of the variables: $contents =~ s/\$(\w )/$variables{$1}/g
.
But there are some detailed decisions to be made:
When should the variables be expanded – directly when the file is read, or after the file structure has been parsed into a hash? It is typically safer to expand the variables at a later stage, in case the variables would contain the
===
delimiter. For example, to expand variables in the keys and values of a hash table:my %expanded = map { s/.../.../gr } %parsed;
Note the use of the
/r
flag so that the regex substitution returns the replaced result instead of modifying the input string, here the implicit variable$_
due to using themap
operator.What happens if the file references a variable that doesn't exist? Then it might make sense to
die
with an error message. We can include the code in the replacement part of the regex substitution with the/e
flag:$contents =~ s{\$(\w )}{ $variables{$1} // die "Unknown variable: $1" }ge