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

Now, can any monk more wise or at least more educated than I, explain why?

I was trying to make a little wrapper routine for calls to Win32::OLE methods to combine them with error checks, so I don't have to rewrite the error checking code for each call.

Here is a baby example using my first attempt at OLECheck:

#!c:/sw/perl/bin/perl.exe use warnings; use strict; use Win32::OLE; our $project; sub OLECheck (&$) { my ($sub,$msg) = @_; my $result = eval &$sub; die "Couldn't $msg: $@" if $@; my $error = Win32::OLE->LastError(); die "Couldn't $msg: $error" if $error; $result; } OLECheck {$project = Win32::OLE->new("ISWiAutomation9.ISWiProject");} "instantiate the Developer Automation Interface"; print "success!\n";
Instead of "success!" I got:
Couldn't instantiate the Developer Automation Interface: Can't modify +constant item in scalar assignment at (eval 2) line 2, at EOF Bareword "Win32::OLE" not allowed while "strict subs" in use at (eval +2) line 1.
Changing the eval line like so:
my $result = eval {$sub->()};
fixes the problem.

Even though my immediate problem is solved, I'm still curious as to why the original failed in the way that it did.

--DrWhy

"If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."

Retitled by Steve_p from 'I solved my problem!'.

Replies are listed 'Best First'.
Re: Confusion with eval
by eibwen (Friar) on May 04, 2005 at 17:17 UTC

    Consult perlfunc, which contains this excerpt from eval:

    With an "eval", you should be especially careful to remember what's being looked at when:

    eval $x; # CASE 1 eval "$x"; # CASE 2 eval '$x'; # CASE 3 eval { $x }; # CASE 4 eval "\$$x++"; # CASE 5 $$x++; # CASE 6

    Cases 1 and 2 above behave identically: they run the code contained in the variable $x. (Although case 2 has misleading double quotes making the reader wonder what else might be happening (nothing is).) Cases 3 and 4 likewise behave in the same way: they run the code '$x', which does nothing but return the value of $x. (Case 4 is preferred for purely visual reasons, but it also has the advantage of compiling at compile-time instead of at run-time.) Case 5 is a place where normally you would like to use double quotes, except that in this particular situation, you can just use symbolic references instead, as in case 6.

Re: Confusion with eval
by DrWhy (Chaplain) on May 04, 2005 at 18:06 UTC
    Okay, I got it. The first version was simply executing the $sub and then passing the results of that into eval -- or the first item returned. That is why it was appearing to work for me in some cases (not shown in the original example), but producing odd errors at other times.

    --DrWhy

    "If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."