user3350919
user3350919

Reputation: 253

How to assemble a file full path when both the dir path and the file name are variables?

I have a perl script that get's 2 dir names, and go through all the files in the first dir, and find them at the second dir (and do some proccesing there).

the following:

opendir( SourceDir,  $first_dir);
my @files = readdir(SourceDir);
foreach my $file (@files){
  my $orig_file = $second_dir"/"$file;
  print $orig_file . "\n";

}

` but my $orig_file = $second_dir"/"$file; does not work,

how can I assem ble a full path presentation of my file in the second dir?

thanks Shahar

Upvotes: 0

Views: 54

Answers (2)

Miguel Prz
Miguel Prz

Reputation: 13792

my $orig_file = $second_dir"/"$file; #<-- wrong

you should write:

my $orig_file = $second_dir . "/" . $file;

or this:

my $orig_file = "$second_dir/$file";

Upvotes: 2

Miller
Miller

Reputation: 35198

You either need to do string interpolation or concatenation.

  • my $orig_file = "$second_dir/$file"; # Interpolated variables
  • my $orig_file = $second_dir . "/" . $file; # Concatenated variables

Note, be sure to include use strict; and use warnings in EVERY script. Additionally, be sure to include use autodie; anytime you're doing file or directory processing.

The following is a clean up of your script:

use strict;
use warnings;
use autodie;

my $first_dir = '....';
my $second_dir = '....';

open my $dh, $first_dir;
while (my $file = <$dh>) {
    my $orig_file = "$second_dir/$file";
    print $orig_file . "\n";
}

Upvotes: 2

Related Questions