Hi, On Tue, Jul 26, 2011 at 01:01:54PM +0300, Shlomi Fish wrote: > 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. Done. > > 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: I added a check to verify there's no naughty stuff going on. > > 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 . >
Thank you all for the replies. I used the above mentioned eval-$@ solution which was absolutely working fine. Thanks again! Nikolaus -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/