suekawar has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks , I am trying to grep with the latest directory that maches my string. for example when I do :
ls -lrt drwxrwxrwx 2 do ba 96 Feb 10 04:59 PC_03021001_MDS_RF +_job drwxrwxrwx 2 do ba 96 Feb 10 05:02 PC_0011814_AVE_RF_ +1.5 drwxrwxrwx 2 do ba 96 Feb 10 05:12 US_03029_AVE_RF_42 +3.5 drwxrwxrwx 2 do ba 96 Feb 10 05:24 AT_030_DAE_RF_4
I am trying to chdir to the latest dir with the word PC in the front . so it should be PC_0011814_AVE_RF_1.5 so how can I get to that LATEST directory with only knowing part of the directory name :
chdir "/diro/col/PC*" or die" can't change";
thanks for help .. let me know if the question is not clear. thanks again

Replies are listed 'Best First'.
Re: greping from lists
by Fletch (Bishop) on Feb 17, 2003 at 16:56 UTC

    The easiest way to do what you want is to use grep to winnow out files beginning with `PC', then sort them by modification time and pick the first one from that sorted list.

    opendir( FOO, $somedir ) or die "Can't opendir $somedir: $!\n"; my @PC_dirs = grep /^PC/ and -d "$somedir/$_", readdir( FOO ); closedir( FOO ); my $most_recent = (map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, -M "$somedir/$_" ] } @PC_dirs)[0];
Re: greping from lists
by steves (Curate) on Feb 17, 2003 at 17:01 UTC

    You can read the parent directory:

    my $dir = "whatever"; local *DIR; my $file; my $newest; my $path; opendir(DIR, $dir) or die "Failed to open $dir: $!\n"; while (defined($file = readdir(DIR))) { $path = "$dir/$file"; if ( (-d $path) && ($file =~ /^PC/) ) { $newest = $path if ( !defined($newest) || ((stat($path))[9] > (stat($newest))[9]) ); } } closedir(DIR); chdir($newest);

    This may be easier using File::Find and I'd probably turn it into a callable sub in either case.

Re: greping from lists
by graff (Chancellor) on Feb 17, 2003 at 17:35 UTC
    It seems clear that Fletch has the right answer for you, but if you happen to be one of those people who likes to use existing shell utilities do your work for you, you could try it like this:
    $destination = (split /\n/, `ls -dt /path/to/targets/PC*`)[0]; chdir $destination;
    The options given to "ls" are: "d": list just the names of directories, not their contents; "t": order the listing newest-to-oldest. (You were using "r" with "t" which meant list the entries oldest-to-newest, and you weren't limiting the command to just entries starting with "PC".) Note that you don't need to include the "l" option (long, detailed format) to make "ls" order its output by date.
      thanks all for the help