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

Hi, new here... I'm using perl to digest cfg files and drive some excel reports we produce. I'm now trying to make the script a bit more robust and handle things like missing sheets, named cells etc. VB has an on error to catch these errors. How do I do the same with perl? What I'm picturing is a generic error handler to field OLE errors and 'do the right thing' based on the specific error. thx, -Tom

Replies are listed 'Best First'.
(jeffa) Re: OLE error handling
by jeffa (Bishop) on Jun 22, 2001 at 19:27 UTC
    VB likes to make this nice and available, it just seems so easy with VB, until you need real power. People tend to dismiss Perl's exception handling and error catching mechanisms as brute force - but they are flexible and powerful. I have found that the latter is more desireable.

    In Perl, all expressions evalute to a value - if that value is non-zero, then it is true. Say you want to know if a worksheet is missing:

    # lots of code assumed before this line my $oWkS = $oBook->{Worksheet}[$sheet] or die "sheet doesn't exist";
    It's really that simple. If it's exception handling you need, Perl provides that via eval and die:
    eval { open FILE, $file; } die "$file did not open for reading" if $@;
    When you place you questionable code inside an eval block, any errors will be stored in $@ - the trick is you have to check $@ _immediately_ after a possible exception, the next exception will wipe out the first.

    When looping, the next and last commands are very valuable:

    while (1) { next if $_ = 'just skip this'; last if $_ = 'fatal exception'; }
    That was a very simple and pointless example just to get the point across. next and last are very consise ways to handle exceptions.

    You can also find CPAN modules that take care of this for you, such as Error.

    If you feel you need a centralized repository for errors, just create your own Errors Object. I discussed this very thing in (jeffa) Re: style for returning errors from subroutines, but that solution will have to be re-constructed to fit your needs. The idea is there, however.

    Good luck, i hope my pointers help, i am sure that others will supply alternatives . . . :)

    Jeff

    R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
    L-L--L-L--L-L--L-L--L-L--L-L--L-L--