menteith
menteith

Reputation: 678

Perl: not creating an empty final file when a folder is empty

I have the following script to make pdf from jpgs. It works fine but when a folder is empty or has no jps, it creates and empty pdf file. How to avoid it?

#!/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);

Upvotes: 0

Views: 75

Answers (1)

user3458
user3458

Reputation:

I am sure you could do something with glob, but it may be easier to just add

my $someFilesFound;

before the while loop. Set it to 1 in the loop body and test it before invoking saveas.

Upvotes: 3

Related Questions