简体   繁体   中英

How to open multiple files in Perl

Guys im really confused now. Im new to learning Perl. The book ive read sometimes do Perl codes and sometimes do Linux commands.

Is there any connection between them? (Perl codes and linux commands)

I want to open multiple files using Perl code, i know how to open a single file in Perl using:

open (MYFILE,'somefileshere');

and i know how to view multiple files in Linux using ls command.

So how to do this? can i use ls in perl? And i want to open certain files only (perl files) which dont have file extension visible (I cant use *.txt or etc. i guess)

A little help guys

Use system function to execute linux command, glob - for get list of files.

http://perldoc.perl.org/functions/system.html

http://perldoc.perl.org/functions/glob.html

Like:

my @files = glob("*.h *.m"); # matches all files with a .h or .m extension
system("touch a.txt"); # linux command "touch a.txt"

Directory handles are also quite nice, particularly for iterating over all the files in a directory. Example:

opendir(my $directory_handle, "/path/to/directory/") or die "Unable to open directory: $!";

while (my $file_name = <$directory_handle>) {
  next if $file_name =~ /some_pattern/; # Skip files matching pattern
  open (my $file_handle, '>', $file_name) or warn "Could not open file '$file_name': $!";
  # Write something to $file_name. See <code>perldoc -f open</code>.
  close $file_handle;
}
closedir $directory_handle;

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