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

I've recently just implemented OO error handling using Error.pm. I've been implementing code which throws errors if something fails of the form:-
#$HashOfTNBs{$rec_count}{$subindex} = $1 or throw TNBCriticalColExcept +ion("Cannot add multiple key entry in hash array");
The problem is that when $1 = 0 it throws the error - rightly so.

However even when I bracket the assignment the same happens.

How can I check whether a statement executes successfully without having to wrap it in a mod and create a return code and then check it.

I'm sure there is a simple one liner way of doing this but I cant quite get the syntax right.

tks

Edit by tye to preserve formatting

Replies are listed 'Best First'.
Re: "0" or throw problem (wrong check)
by tye (Sage) on Mar 10, 2003 at 17:25 UTC

    Well, if you want to throw when the string is empty, then you have several choices:

    length( $HashOfTNBs{$rec_co­unt}{$subindex} = $1 ) or throw TNBCriticalColExcept­ion( "Cannot add multiple key entry in hash array" );
    or
    if( "" eq ( $HashOfTNBs{$rec_co­unt}{$subindex} = $1 ) ) { throw TNBCriticalColExcept­ion( "Cannot add multiple key entry in hash array" ); }
    to show just two.

    But you are checking $1 which makes me think that perhaps you should instead be checking the success of the regular expression that you hope is setting $1. If the regular expression fails then $1 is left unchanged which would leave it undefined if you have no other regular expressions run before that (which might make you think that your code is working better than it is) but can also leave $1 set to the results of some previous regular expression.

                    - tye
Re: Eval Issue
by Elian (Parson) on Mar 10, 2003 at 16:40 UTC
    What are you trying to do? If it's trying to wrap the assignment itself in an error checker that throws an exception, you'll have to do something like:
    eval {#$HashOfTNBs{$rec_count}{$subindex} = $1}; if ($@) { throw TNBCriticalColException("Cannot add multiple key entry in ha +sh array"); }
    There's no other way around that, since assignment returns the assigned value, rather than a true/false "it worked" value.
Re: "0" or throw problem
by jonadab (Parson) on Mar 11, 2003 at 12:19 UTC
    defined ($foo = bar()) or throw "Undefined bar: $! ($@).";
    for(unpack("C*",'GGGG?GGGG?O__\?WccW?{GCw?Wcc{?Wcc~?Wcc{?~cc' .'W?')){$j=$_-63;++$a;for$p(0..7){$h[$p][$a]=$j%2;$j/=2}}for$ p(0..7){for$a(1..45){$_=($h[$p-1][$a])?'#':' ';print}print$/}