Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl open files with variable in filename

Tags:

arrays

file

perl

I try to open a list of files in a folder. Eventually I want to insert a HTML-Snippet in it. So far I can open the folder and read the list in an array. That´s fine. But when I try to open the files by using a variable as filename, I get an error message every time ("permission denied"). No matter if I use $_ or other variations of putting the values of list items in variables. I have found similar questions here, but didnt find the solution so far. Here is my code:

use strict;
use warnings;

my ($line);

opendir (FOLDER,"path/to/folder/./") or die "$!";
my @folderlist = readdir(FOLDER);
my @sorted_folderlist = sort @folderlist;
close(FOLDER);

foreach (@sorted_folderlist) {
  my $filename = $_;
  open (READ, ">", "path/to/folder/$filename") or die "$!";
  # do something
  close (READ);
}

What is the mistake here? And how would I open files with using a variable as filename?

Pjoern

Here is my changed code in order to answer 1:

my $dh; 
opendir $dh, "dir/./" or die ... 
my @folderlist = grep { -f "dir/$_" } readdir $dh; 
close $dh; 
my @sorted_folderlist = sort @folderlist; 

foreach my $filename (@sorted_folderlist) { 
  open my $fh, "<", "dir/$filename" or die ... 
  open my $writeto, ">", "new/$filename" or die ... 
  print $writeto "$fh"; 
  close $fh; 
  close $writeto; 
}
like image 380
Pjoern Avatar asked Dec 15 '17 21:12

Pjoern


People also ask

How do I open a file for reading in Perl script?

Perl open file function You use open() function to open files. The open() function has three arguments: Filehandle that associates with the file. Mode : you can open a file for reading, writing or appending.

What is $_ in Perl?

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }

How do I open multiple files in Perl?

open (MYFILE,'somefileshere');


1 Answers

You have several issues in your code.

The first, causing the error, probably, is that readdir() will return . and .. also, but these are directories. So you try to write to directory/..

Second, your error message contains $!, which is good, but you don't output the filename. Then you would have seen your mistake.

Third, you call a filehandle you open for writing READ.

Also, you should use lexical filehandles nowadays.

use strict;
use warnings;

opendir my $dh, "dir" or die $!;
# read all files, not directories
my @folderlist = grep { -f "dir/$_" } readdir $dh;
close $dh;
my @sorted_folderlist = sort @folderlist;

foreach my $filename (@sorted_folderlist) {
    open my $fh, ">", "dir/$filename" or die "Could not write to dir/$filename: $!";
    print $fh "foo...\n";
    close $fh;
}
like image 77
tinita Avatar answered Oct 29 '22 12:10

tinita