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

Hi Monks!
I am trying to do something I don't even know if it will be possible, but maybe someone here have an alternative or a better solution for it. I have directories with pdf files and the name of this control txt file has to be the name of one of these files from these directories. I need to first open these directories, extract the name from the first file found, replace the extension .pdf to .txt. The problem I have is how to create this control txt file name after going inside of the directories.
Here is the code I hope I made myself clear:
#!/usr/bin/perl -w use strict; use File::Basename; use File::Slurp qw(read_dir); my $control_file; my @acc_files; my ($path, $name); my @acc_dir = qw( accountdir_a accountdir_b); for my $acc (@acc_dir) { push @acc_files, grep { -f } read_dir( $acc, prefix => 1 ); } open XFILE, ">'$control_file'" or die $!; foreach my $account(@acc_dir) { chomp($account); if($account =~/(.*?)\/([^\/]+)$/) { $path=$1; $name=$2; } # name of the control file here::: ($control_file = $name) =~ s/(\.)([^.]+$)/$1txt/; # creating log file::: print XFILE "$name\n"; } close (XFILE);
Thanks for looking!

Replies are listed 'Best First'.
Re: FIle name help!
by wink (Scribe) on Sep 01, 2011 at 03:04 UTC

    From reading your description, it sounds like you have filename1234.pdf and you need to change it to filename1234.txt, is that right? Why not:

    $name =~ s/pdf$/txt/;

Re: FIle name help!
by aaron_baugher (Curate) on Sep 01, 2011 at 20:19 UTC

    For starters, you're opening the file '$control_file' before assigning anything to that variable, so it's empty. If you 'use warnings', it'll tell you about that. Plus, since you've got single quotes inside double quotes, you actually get a file named with two single quotes. Probably not what you want.

    Because you open the control file outside your loop, I'm not sure whether you want a single file containing a list of names created from all your PDF files (what your code seems designed to try to do), or a different control file to match each PDF (what your description sounds like). Can you clarify?

    Edited to add: Upon re-reading, it appears that you want a single control file, named after the "first" file found in the directories. (Whether you want the first one alphabetically, or by age, or by some other sorting factor, I don't know, so I'll just assume whichever one read_dir() returns first will do.) In that case, use $acc_files[0] for your control file name, after changing the suffix:

    ($control_file = $acc_files[0]) =~ s/pdf$/txt/;
Re: FIle name help!
by Lotus1 (Vicar) on Sep 01, 2011 at 15:17 UTC