<?xml version="1.0" encoding="windows-1252"?>
<node id="181789" title="GOTO considered (a necessary) evil?" created="2002-07-15 10:30:10" updated="2005-07-28 14:10:26">
<type id="120">
perlmeditation</type>
<author id="128665">
gav^</author>
<data>
<field name="doctext">
&lt;p&gt;We were reviewing the following code for part of a membership site
I've been working on when another developer pointed out that I used
a &lt;i&gt;goto&lt;/i&gt; and this was evil. The code is:&lt;/p&gt;

&lt;code&gt;RE_TIE: eval {
    tie %session, 'Apache::Session::MySQL', $session, {
        Handle =&gt; HH::DB-&gt;db_Main, LockHandle =&gt; HH::DB-&gt;db_Main
    }
};

if ($@) {
    if ($@ =~ /^Object does not exist/) {
        $session = undef;
        goto RE_TIE;
    } else {
        print $cgi-&gt;header;
        die_nice('Database Error', 'Unable to connect at this time');
    }
}
&lt;/code&gt;
&lt;readmore&gt;
&lt;p&gt;The &lt;i&gt;goto&lt;/i&gt; is to handle a "shouldn't really happen" case (somebody
sending us a session id which is invalid). I like the use of &lt;i&gt;goto&lt;/i&gt; because
it doesn't distract from the "normal" case which a loop would. He suggested:&lt;/p&gt;

&lt;code&gt;my $tied = 0;
while (!$tied) {
    eval {
        tie %session, 'Apache::Session::MySQL', $session, {
        Handle =&gt; HH::DB-&gt;db_Main, LockHandle =&gt; HH::DB-&gt;db_Main
    };
    if ($@) {
        if ($@ =~ /^Object does not exist/) {
            $session = undef;
        } else {
            print $cgi-&gt;header;
            die_nice('Database Error', 'Unable to connect at this time');
          }
    } else {
        $tied = 1;
    }
}
&lt;/code&gt;

&lt;p&gt;Personally I think this is harder to read and it makes you read through
to work out how the loop is exited.&lt;/p&gt;

&lt;p&gt;I was wondering what the general consensus here was, is &lt;i&gt;goto&lt;/i&gt; (in this case) really
evil?&lt;/p&gt;

&lt;p&gt;gav^</field>
</data>
</node>
