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

I am simply trying to get an error code to pass to a redirected page. Basically, I want "3" to become part of the redirect for my __DIE__

My code is as follows:
$sqlquery = "SOME UPDATE STATEMENT"; my $newsth = $dbh->prepare($sqlquery); $newsth->execute or die "3";

and the DIE handler...
$SIG{__DIE__} = sub { print $query->redirect(-location=>"$redirecturl?error=@_"); };

How do I get the "3" to pass to my redirect?

Replies are listed 'Best First'.
Re: __DIE__ easy CGI question
by batkins (Chaplain) on Sep 30, 2003 at 01:46 UTC
    I'm not sure if a __DIE__ handler is the best way to go. I would use an eval block to trap the die. Something like this:
    eval { $sqlquery = "SOME UPDATE STATEMENT"; my $newsth = $dbh->prepare($sqlquery); $newsth->execute or die "3"; }; print $query->redirect(-location=>"$redirecturl?error=$@") if $@;
    When the die is called, the eval block will exit and $@ will be set to "3". If there is no error, then $@ will be set to the empty string.

    If I were a terrorist I'd mainly be afraid of polar bears. Because at the moment, I'm mainly afraid of polar bears, and I can't really see why that would change.
    - slashdot
Re: __DIE__ easy CGI question
by sgifford (Prior) on Sep 30, 2003 at 03:07 UTC
    The code you have looks about right. This works OK:
    #!/usr/bin/perl -w use strict; $SIG{__DIE__} = sub { print "redirecturl?error='@_'\n"; exit(1); }; die "3";
    produces:
    redirecturl?error='3 at /tmp/t112 line 10.
    '
    

    The problem is that you also get a line number with your error message. You can either eliminate that with a regex, or you can use die "3\n" and then use chomp to eliminate the newline. The @_ variable is readonly, so you'll have to make a copy:

    #!/usr/bin/perl -w use strict; $SIG{__DIE__} = sub { my $why = shift; $why =~ s/( at.*)?\n$//; print "redirecturl?error='$why'\n"; exit(1); }; die "3";
    produces
    redirecturl?error='3'
    
    whether you use die "3" or die "3\n".