Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Calling a Variable from another file

by monkfan (Curate)
on Jun 22, 2005 at 13:35 UTC ( #469004=perlquestion: print w/replies, xml ) Need Help??

monkfan has asked for the wisdom of the Perl Monks concerning the following question:

For example I have a hash created with Data::Dumper, stored in a variable $res, in a file called ""
use strict; #File name: my $res = { # a very big hash reference # created with Data::Dumper # with a very long processing time };
And I would like to use that variable for my "" file.
Can we do that? Just as we call a function. I hope that`s a reasonable question. Thanks beforehand.

Replies are listed 'Best First'.
Re: Calling a Variable from another file
by tlm (Prior) on Jun 22, 2005 at 13:47 UTC

    I've never actually done what I'm about to propose, so there may be pitfalls I haven't thought of, but assuming that the assignment to my $res is the last executable statement in, I would try something like

    my $whatever = do '';
    That should be equivalent to assigning to $whatever the value returned by eval'ing the contents of

    I question the whole approach on design grounds, however. See this thread for some possible alternatives.

    the lowliest monk

Re: Calling a Variable from another file
by halley (Prior) on Jun 22, 2005 at 13:44 UTC
    The my keyword makes the variable into a private "lexical" variable. Code in other packages cannot refer to it by name.

    The our keyword works similarly, but turns the name into a package variable. Then you can refer to it by its package. For example, if declared inside package MyPackageName, then other packages can refer to it as $MyPackageName::res.

    I could just tell you that files included with require don't need package names and all of that, but that path leads to madness when your project grows.

    [ e d @ h a l l e y . c c ]

Re: Calling a Variable from another file
by davidrw (Prior) on Jun 22, 2005 at 13:43 UTC
    This isn't really the best way to store/pull back stuff, but it is quick & dirty (basically just eval your $res string):
    # storing: my $data = ... ; # some big hairy data structure open FILE, ">$filename" or die "can't open '$filename': $!"; print FILE Dumper($data); close FILE; # retrieving: open FILE, "$filename" or die "can't open '$filename': $!"; my $VAR1; eval do{ local $/=undef; <FILE> }; # your big hairy data structure is in $VAR1 now close FILE;
    You can also play with the Data::Dumper syntax so that the string had "$data =" instead of "$VAR1 =".

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://469004]
Approved by ghenry
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2021-04-13 01:22 GMT
Find Nodes?
    Voting Booth?

    No recent polls found