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

Hello,
I am little confused, so I hope this makes sense. I tried to find a thread to answer this already, but didn't have any luck...
I am running a require on a variable name within an eval. Here is a simplified version:
eval qq{ $file = 'foo.pl'; # foo has errors in it require "$file"; } dienice("that code is busted because: $@") if $@;
but that doesn't work for me. The dienice never gets triggered. Now here's my confusion:
When a require fails because the code being slurped-in has a missing ; or some other error its supposed to exit out and print $@, right?
But in this case that exit is trapped by the eval. Then the eval evaluates to false because the return wasn't 1, because the code failed in the require right?
Since the eval failed, I would expect the $@ to persist and be detected and printed by the dienice(), therefore telling me what the error was in foo.
I tried wrapping the require in an eval, but then I couldn't double quote the variable and there was a syntax error. I also tried putting the dienice inside the eval, but it still didn't work. Can someone set me straight here?

Thanks,
Alex
p.s.- this is my fourth question since finding the monks, and this place is so unbelievably helpful I'm stunned. I've been just reading random threads for a couple weeks now and am learning TONS. Just a quick thanks to everyone. :)

Replies are listed 'Best First'.
Re: capturing $@ from an eval'd require
by chromatic (Archbishop) on Jun 01, 2002 at 02:29 UTC
    Drop eval STRING; use eval BLOCK:
    eval { my $file = 'foo.pl'; require $file; };
    As broquaint points out, $file will be interpolated into the string before the eval runs. To see what you're really doing, try this:
    my $notwhatiwant = qq{ $file = 'foo.pl'; # foo has errors in it require "$file"; }; print "<$notwhatiwant>\n"; eval $notwhatiwant; dienice("that code is busted because: $@") if $@;
    I think you'll be surprised.
      Thanks a lot guys! The code is working great and I have a much clearer understanding of qq{}. This is the second time chromatic has contributed to solving a tricky bit for me this week - awesome.
      Thanks, alex
Re: capturing $@ from an eval'd require
by broquaint (Abbot) on Jun 01, 2002 at 00:28 UTC
    Are you sure foo.pl is not in your PERL5LIB path? Also do you have any $SIG{__DIE__} handlers in your script? Here's some example code that works as expected for me
    # foo.pl print "this is a "syntax" error"; # test.pl eval q{ my $fl = "foo.pl"; require "$fl"; }; __output__ Bareword found where operator expected at foo.pl line 1, near ""this i +s a "syntax" (Missing operator before syntax?) String found where operator expected at foo.pl line 1, near "syntax" e +rror""
    Also note that your qq{} is being interpolated so $file will be seen in your string as whatever it's value is.
    HTH

    _________
    broquaint