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

How can I go about finding what files are in a directory, and then creating a new file that is one number greater than the last file in the directory...

Also how can I write files that have trailing 0's if they arn't already 6 characters large?...

Directory Structure..

0000001.dat
0000002.dat
0000102.dat


I want to do something like that

Replies are listed 'Best First'.
Re: file/directory operations
by belg4mit (Prior) on Dec 16, 2001 at 04:58 UTC
Re: file/directory operations
by mrbbking (Hermit) on Dec 16, 2001 at 07:44 UTC
    Once you've got your list of files, here's One Way To get the next filename to use:
    #!/usr/bin/perl -w use strict; my @files = qw( 0000002.dat 0000102.dat 0000001.dat ); my $highest_file = ''; my $test_file = ''; foreach $test_file( @files ){ if( $test_file gt $highest_file ){ $highest_file = $test_file; } } print "highest numbered file is $highest_file\n"; my $base_name = $highest_file; $base_name =~ /^(\d+)(.+)/; $base_name = $1; my $suffix = $2; $base_name++; print "Next file name is $base_name$suffix\n";
Re: file/directory operations
by Zaxo (Archbishop) on Dec 16, 2001 at 23:25 UTC

    Apply 'glob' to get a list of filenames matching a pattern. From your example file names, I assume you mean "leading 0's". That permits perl's builtin 'sort' to find the largest numbered file name. Then extract the number, add one, and open the new file to write.

    use Fcntl qw(:DEFAULT :flock); my $path = "/path/to/data/"; my $pattern = "[0-9]" x 7; # Every program which creates a datfile here must honor dat.lock # take the lock before we read names my $pathlock = "${path}dat.lock"; open LOCK, "> $pathlock" or die $!; flock LOCK, LOCK_EX or die $!; my @lastfile = sort glob("${path}${pattern}.dat"); my ($nextnum) = $lastfile[-1] =~ /(\d{7})\.dat$/; $nextnum += 1; my $nextname = sprintf "%07d.dat", $nextnum; # answers question 2 open NEWDAT, "> ${path}${nextname}" or die $!; # ... close NEWDAT or die $!; close LOCK or die $!;
    Tested. For compatibility with older Perl, I've avoided the superior 3-arg open and autovivifying lexicals as file handles.

    After Compline,
    Zaxo