my %lists_by_size; # get list of file names into @inp_files for my $file ( @inp_files ) { my $group = get_page_count( $file ); push @{$lists_by_size{$group}}, $file; } for my $group ( keys %lists_by_size ) { # open output pdf (or output zip file) for this group for my $file ( @{$lists_by_size{$group}} ) { # use sort here if you like # append this file to the output } # close the output }