简体   繁体   中英

How to open a file from different directory in perl?

i am very new to perl, so I would like to know if there is a way to

  1. Open a file from a different directory (not the same directory as the perl script.pl for example)

  2. open multiple files that have the same name, eg sameName.txt, under the same parent directory but have different sub directory, eg

     directory: - /alias/a/1/sameName.txt - /alias/b/1/sameName.txt - /alias/c/1/sameName.txt 

    for example as above, but at the same time, there is also the same file, sameName.txt in other directory which I don't want, eg

     directory: - /alias/a/2/sameName.txt - /alias/b/2/sameName.txt - /alias/c/2/sameName.txt 

    How can I automatically search the directory which the user want, using user input <STDIN> , not hard-coded into the script perl.pl for example, the user want all the sameName.txt files which had in the directory /1/sameName.txt, but with different parent, which is ab and c folder. I want to make it automatically read those files sameName.txt which is located in different folder, so that the user doesn't need to adjust the script every time there is a new path like d/1/sameName.txt created.

  3. if I want the data in these files with the same name with different directories, should I loop it, save into arrays for example, or should i copy all the contents and append it to a single file? because i need to match the data between the files which i have done the script.

  1. You can open a file from anywhere that you like.

The filename argument is a path and you associate that with a filehandle to access its data:

  my $path = '/alias/a/1/sameName.txt';
  open my $fh, '<', $path or die "Could not open $path: $!";
  1. Perl doesn't care if another file in a different directory has the same name.

You distinguish them with a different file handle:

  my $path2 = '/alias/a/2/sameName.txt';
  open my $fh2, '<', $path or die "Could not open $path: $!";

You can construct that second path by grabbing the filename portion of the first path and putting it together with the other directory. These are core Perl modules that should already be there:

  use File::Basename;
  use File::Spec::Functions;

  my $other_dir = '/alias/a/2';
  my $basename = basename( $path );   # sameName.txt
  my $path2 = catfile( $other_dir, $basename );
  1. Not quite sure what you are trying to do.

You might be interested in Learning Perl or the other resources at learn.perl.org .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM