Advertisement
hakonhagland

so-68696767

Aug 11th, 2021
2,018
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.45 KB | None | 0 0
  1. use feature qw(say);
  2. use strict;
  3. use warnings;
  4. use experimental qw(signatures);
  5.  
  6. {
  7.     my @items = map { +{item => "item_" . $_} } 1..10;
  8.     my @files; # all files
  9.     my @items_not_found; # items whose associated file was not found
  10.     my @idx_not_found; # indexes of items not found
  11.     for my $i (0..$#items) {
  12.         my $item = $items[$i];
  13.         my $associated_file = search_associated_file( $item );
  14.         if (defined $associated_file) {
  15.             $files[$i] = $associated_file;
  16.         } else {
  17.             push @items_not_found, $item;
  18.             push @idx_not_found, $i;
  19.         }
  20.     }
  21.  
  22.     # The program now invokes an external process to generate the associated files
  23.     #   for the missing items:
  24.     @files[@idx_not_found] = generate_associated_files_of ( \@items_not_found);
  25.  
  26.     my $fn = 'associated_files.txt';
  27.     open ( my $fh, '>', $fn ) or die "Could not open file '$fn': $!";
  28.     for my $file (@files) {
  29.         say $fh "$file";
  30.     }
  31.     close $fh;
  32. }
  33.  
  34. sub generate_associated_files_of($items) {
  35.     my @files;
  36.     for my $item (@$items) {
  37.         my ( $idx ) = $item->{item} =~ /item_(\d+)/;
  38.         die "Unexpected index" if !defined $idx;
  39.         push @files, "file_$idx";
  40.     }
  41.     return @files;
  42. }
  43.  
  44. sub search_associated_file($item) {
  45.     my ( $idx ) = $item->{item} =~ /item_(\d+)/;
  46.     my %not_ok_idx = map { $_ => 1} 4,5,7;
  47.     return undef if $not_ok_idx{$idx};
  48.     return "file_" . $idx;
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement