views:

175

answers:

4

can you convert this python code to perl code (i search about it but dont find a good result)

for i in xrange(20):
    try:
        instructions
    except :
        pass

Thanks

+3  A: 

You should look at the Try::Tiny module. Also your question really should be fleshed out some more. You don't give us any info at all to help you. What problem are you trying to solve by doing this?

Daenyth
A: 

As far as I know it's not built into perl, but there is at least one module for implementing try/catch behaviour

http://search.cpan.org/~nilsonsfj/Error-TryCatch-0.07/lib/Error/TryCatch.pm

amir75
do you know a function like it in perl ? a function like try: ... except: please help me
Eva Feldman
eh? I just gave you one. It just uses the word 'catch' instead of 'except'
amir75
Downvote for recommending a source filter module.
daxim
@daxim: fair enough. Thanks for explanation, I learnt something
amir75
+13  A: 
use strict;
use warnings;
use Try::Tiny;

for my $i (0 .. 19){
    try {
        print "1 / $i = ", 1 / $i, "\n";
    }
    catch {
        print "Doh! $_";
    }
}
FM
Wouldn't it make more sense to do this with a C-style for loop? (Perl does have those, right?)
David Zaslavsky
Why in the world would you do this instead of `for (0..20)`? If your answer is "optimization", you're at least two kinds of wrong.
hobbs
@David and @hobbs Yes, you are absolutely right. I've got my head so deep into learning Python these days that I'm getting rusty at Perl! Answer edited.
FM
That's a much better answer after the edit. +1
SpoonMeiser
heh, I really should brush up on Perl myself. +1
David Zaslavsky
+7  A: 

There are packages that provide better exception handling then is directly implemented in the language, but without using anything like that, you'd do something like this:

foreach my $i (0..19) {
    eval {
        # instructions
        print $i;
        if ($i == 5) {
            die("boo");
        }
        1;
    } or {
        # exception handling
        print $@;
    }
}

So you die instead of raise in an eval block, and then examine the $@ variable afterwards to see if an error was thrown.

I would recomend writing an exception class to throw though, instead of using strings.

SpoonMeiser
You are better off to use `eval { foo(); 1 } or handle_exception();` This guarantees you will trap an exception even if the value of $@ is changed somehow. Better to use Try::Tiny though.
daotoad
@daotoad, I think doing it that way might be worth a seperate answer. I wanted to make sure that a method that didn't involve additional packages was represented in the answers, even if it wasn't the best answer, because knowing how to do this is important, I think.
SpoonMeiser