我有以下脚本从jpgs制作pdf。它工作正常,但当文件夹为空或没有jps时,它会创建并清空pdf文件。如何避免呢?
#!/usr/bin/perl
use PDF::API2;
use strict;
# assume all just one directory path
my $folder = join(' ', @ARGV);
# deal with dos paths
$folder =~ s|\\|/|g;
$folder =~ s|/$||;
my $pdf_file = $folder . '.pdf';
die "Not a folder!\n" unless -d $folder;
die "There's already a pdf of that name!\n" if -f $pdf_file;
my $pdf = PDF::API2->new;
opendir DIR, $folder;
while(my $file = readdir DIR) {
next unless $file =~ /\.je?pg$/i;
my $jpg = $folder . '/' . $file;
my $image = $pdf->image_jpeg($jpg);
my $page = $pdf->page();
$page->mediabox(0,0,$image->width, $image->height);
$page->trimbox(0,0,$image->width, $image->height);
my $gfx = $page->gfx;
$gfx->image($image, 0, 0);
}
close DIR;
$pdf->saveas($pdf_file);
答案 0 :(得分:3)
我相信您可以使用glob
执行某些操作,但可以更轻松地添加
my $someFilesFound;
在while循环之前。在循环体中将其设置为1并在调用saveas
之前对其进行测试。