Hi Nikolaus,

On Tue, 26 Jul 2011 11:32:19 +0200
Nikolaus Brandt <nickol...@freenet.de> wrote:

> Hi,
> 
> I'm currently writing a script which contains a subroutine to write
> data to files.
> Currently I use
> open $fh, '>', "$basedir/$userdir/$outfile" or die "Can't write: $!\n";
> which has the disadvantage, that the whole script dies if e.g. the
> userdir is not available. 
> 
> Could you give me an advise how to just exit the subroutine if opening
> the filehandle fails, without exiting the whole script?
> 

To answer your question, look at the return statement:

http://perldoc.perl.org/functions/return.html

You can do:

if (!open my $fh, '>', $path)
{
        return;
}

Another option would be to use eval { ... } and $@ to trap exceptions:

http://perl-begin.org/tutorials/perl-for-newbies/part4/#page--exceptions--DIR

Now a few comments on your code:

1. Normally, you should do: "open my $fh" instead of "open $fh" to limit its
scope.

2. You're interpolating several variables into a
path: "$basedir/$userdir/$outfile", so make sure you sanitise them. If I put in
$outfile e.g: "../../../../etc/passwd", then I'll be able to write
to /etc/passwd. See:

http://webcache.googleusercontent.com/search?q=cache:aEbtJ4YXhVkJ:shlomif-tech.livejournal.com/35301.html%3Fthread%3D29157+code+markup+injection+prevention&cd=1&hl=en&ct=clnk&source=www.google.com

(sorry - livejournal.com is down.)

You may also opt to use what Joel Spolsky describes here:

http://www.joelonsoftware.com/articles/Wrong.html

or perhaps a superior method of making the wrong code behave in an obviously
wrong way (i.e: terminate the program with an error), which will require more
coding in Perl.

Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
My Favourite FOSS - http://www.shlomifish.org/open-source/favourite/

Tcl is Lisp on drugs. Using strings instead of S‐expressions for closures is
Evil with one of those gigantic E’s you can find at the beginning of chapters.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to