Home > Enterprise >  Perl script that takes linux path as input from the user till a directory and need to get the output
Perl script that takes linux path as input from the user till a directory and need to get the output

Time:08-27

I have written perl script that takes linux path as input from user until a certain directory and prints all the directories inside that which have the common name for example, if user input is /user/images/mobile_photos/ inside mobile_photos I have a list of directories that start with image_ like image_user_1,image_user_2,...,image_user_10 and inside each directory there is quality of image like best,good,bad as a string in a file quality.txt. Now I need to get the list of these directories inside a file with the quality of the images next to directory name. Please help me in this regard.

Actual path for one example /user/images/mobile_photos/image_user_1/quality.txt

The user should give input as /user/images/mobile_photos/

The required output inside temp.txt is image_user_1 good image_user_2 bad image_user_3 best image_user_4 best . . . image_user_10 bad

Below is the code attached just for image quality being good `

  #! /usr/bin/perl
    use strict;
    use warnings;
    my $path = <STDIN>;
    my $dir = system ("ls -d $path/image_*/quality.txt "good" > temp.txt");
    print "$dir";
    exit(0);

`

But I am getting the terminal output as /user/images/mobile_photos/ and temp.txt being empty.

CodePudding user response:

No reason to go out to the system for this. It's only far more complicated that way, and there is an extra challenge of getting all the quotes and escapes right

use warnings;
use strict;
use feature 'say';

use File::Glob ':bsd_glob';

my $path = shift // die "Usage: $0 path\n";

my @qual_files = glob "$path/image_*/quality.txt"

say for @qual_files;  # just to see them

# Save list to file
my $out_file = 'temp.txt';
open my $fh_out, '>', $out_file or die "Can't open $out_file: $!";
say $fh_out $_ for @qual_files;
close $fh_out or warn "Error closing $out_file: $!";

The builtin glob has a limited set of metacharacters resembling the shell's. I use File::Glob since it handles things like spaces in filenames nicely, etc.

There are of course yet other ways to read directories and select entries.


Please explain how one decides about "good" vs "bad" (etc) words that the question asks to be written along with filenames.

CodePudding user response:

#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

chomp( my $path = <STDIN> );
opendir my $dir, $path or die "Can't open $path: $!";
while (my $dir = readdir $dir) {
    next unless -d "$path/$dir" && $dir =~ /^image_/;

    if (-f "$path/$dir/quality.txt") {
        open my $q, '<', "$path/$dir/quality.txt"
            or die "Can't open $dir/quality.txt: $!";
        chomp( my $quality = <$q> );
        say "$dir\t$quality";
    } else {
        warn "quality.txt not found in $dir.\n";
    }
}
  • Related