Amy
Amy

Reputation: 1

Open files in specific directory based on inputed file name by user

I am trying to open a file located at \\\server\folder\folder\folder\filename.csv based on user input for the file name. The file will always be a csv file, but the name will be different based on departments. The directory will always be the same, however it is not the directory Perl resides in.

I have been having issues trying to open the file. I have tried to make 2 variables, 1 for the directory and 1 for the file name, but I just get errors thrown when I try to open $directory\\$FileName. I have tried to do an open statement with the directory hard coded in and the file name a variable, but Perl thinks the variable is part of the file name (which makes sense). Is this even possible?

After I have the file open, I have code to run which will edit the file itself (this works fine) and then I want to save the file in a new location. This new location is the same as the directory, but I want to add another folder level to it and then the same file name. Kind of a "before change" file location and an "after change" file location.

print "What is your FULL file name going to be with extension included?";
my $fileInName = <>; 
my $@dirpath= '\\\\Server\\Folder1\\Folder2\\Folder3\\Folder4\\Sorted_files\\';
my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || 
    Win32::OLE->new('Excel.Application', 'Quit'); 
my $Book = $Excel->Workbooks->Open($directory $file); 
my $Sheet = $Book->Worksheets(1);
$Sheet->Activate(); 

That is the code I have now. I tried the following as well:

my $@dirpath= '\\\\server\\folder1\\folder2\\folder3\\call_folder4\\Sorted_files\\$fileName';

Of course I received the "file cannot be found error:

My file open works great if I hard code the entire path name, but I do not want to have 25 seperate scripts out there with the only difference being a file name.

Upvotes: 0

Views: 1672

Answers (2)

ikegami
ikegami

Reputation: 385764

my $@dirpath= '\\Server\Folder1\Folder2\Folder3\Folder4\Sorted_files\';
my $Book = $Excel->Workbooks->Open($directory $file); 

doesn't even compile. It should be:

my $dirpath = '\\\\Server\Folder1\Folder2\Folder3\Folder4\Sorted_files';
my $Book = $Excel->Workbooks->Open("$dirpath\\$file"); 

Upvotes: 0

David
David

Reputation: 6571

Use file::spec module. It's portable and you don't have to worry about escaping slash characters in your path (UPDATE: mostly true, but in this case, you still need to escape the server reference, as shown below, in the assignment to @dirpath).

For example:

use File::Spec::Functions;

# get users file from the cmd line arg
my $usersfile = $ARGV[0];

my @dirpath = qw/\\\server folder folder folder/;
my $filepath = catfile(@dirpath,$userfile);

# test existence
die "file does not exist" unless(-e $filepath);

Upvotes: 0

Related Questions