Reputation: 590
I have a Perl script and I am trying to make it print out the value for $article when it errors. The script looks like:
eval{
for my $article($output =~ m/<value lang_id="">(.*?)<\/value>/g)
{
$article =~ s/ /+/g;
$agent->get("someurl");
$agent->follow_link(url_regex => qr/(?i:pdf)/ );
my $pdf_data = $agent->content;
open my $ofh, '>:raw', "$article.pdf"
or die "Could not write: $!";
print {$ofh} $pdf_data;
close $ofh;
sleep 10;
}
};
if($@){
print "error: ...: $@\n";
}
So if there is no .pdf file the code sends an error which is what I want. But what I need to know is it somehow possible to get the name of the $article that caused the error? I was trying to use some kind of global variable with no luck.
Upvotes: 0
Views: 361
Reputation: 7289
Your script does not need to die, you can just set a flag or save message to the log or store error for late handling.
my @errors=();
................
open my $ofh, '>:raw', "$article.pdf" or do { push @errors,"$article: $!" };
if(-e $ofh) {
# work with the file
}
................
if(@errors) {
# do something
}
Upvotes: 0
Reputation: 50338
If that's your only problem, just declare my $article;
before the eval, and remove the my
from the for
loop. But from your reply to Cornel Ghiban, I suspect it isn't.
Upvotes: 1
Reputation: 7516
Include the file name in the die>/ string:
open my $ofh, '>:raw', "$article.pdf" or die "Could not write '$article': $!";
I assume that you want to write and not read. Unless you have a permission issue or a full file system, a write is likely to succeed and you will never see an error.
Upvotes: 0
Reputation: 902
Why don't you put the eval inside the for loop? Something like this:
for my $article($output =~ m/<value lang_id="">(.*?)<\/value>/g)
{
$article =~ s/ /+/g;
eval{
# ...
}
if ($@) {
print STDERR "Error handling article: ", $article, " ", $!, "\n";
}
}
Upvotes: 4