in reply to Extracting a hash reference from a string
Hi.
As it stands, what you are doing is unlikely to work. The hash in the require block is likely to be lexically scoped to that block (or file). Taking a hash reference to something declared in the other file is only going to work if you explicity force the variable into the current scope before dying, e.g. in 'some_code.pl', you say something like:
%main::err = ( "errno" => 1, "message" => "I'm dead I am", );
Now, assuming package 'main' was the current scope, saying for example $err{errno} would give access to the error hash. But since you have just died out of that file, using data from there might not be the best idea... not to mention the crime of forcing your variables onto another packages scope.
If you really want to use die, then you need to die with something useful. Dying with a normal string representation of a hash is unlikely to prove very useful. Better would be to use Data::Dumper to die with a data structure.
some_file.pl
#!/usr/bin/perl use Data::Dumper; die Data::Dumper->Dump([ { # die with a hash value "errno" => 1, "message" => "I'm dead I am", } ], [ '*err' ]) . "\n"; 1;
Your main program:
# This is our error container my %err; # Rather than "require", we use "do". This stops # the compilation warning from appearing. eval { do "some_code.pl"; die $@ if $@; }; if ($@) { eval $@; # evaluate our "error" string print $err{errno}; # print our errno print $err{message}; # print our message }
I don't really like this method of passing data structures around, but it does work. I suppose that if you have full control over the contents of "some_file.pl" then it is *just* acceptable, but there are far too many evals in this solution. I don't like the thought of accidentally eval'ing a string contained in $@ which I wasn't expecting...
I would strongly suggest using Taint (-T) if this is going to end up in production code. However, there are loads of CPAN modules which encapsulate this sort of throw/catch/try type structure you are creating. Searching for Exception is likely to return one or two which would more than likely fit your purposes.
Hope that helps.
Cheers,
-- Dave :-)
$q=[split+qr,,,q,~swmi,.$,],+s.$.Em~w^,,.,s,.,$&&$$q[pos],eg,print
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Extracting a hash reference from a string
by Anonymous Monk on Mar 23, 2003 at 04:51 UTC |