Search code examples
perlperl-modulefile-handling

Renaming multiple folders using perl


I have text file file.txt which contains 100 words line by line. I need to create 100 directories for those words in file.txt. Each directory name should match each words in a line . I need to create the code using perl for above query.

I tried as follows :

system("mkdir $_") for qw(tuber sp smeg  para);

Solution

  • In general, you shouldn't be using system to do basic file operations in Perl like mkdir. Perl has built ins for this. They're generally faster and have less caveats than calling an external executable.

    use v5.10;
    use strict;
    use warnings;
    
    # This will make file operations throw exceptions so we don't
    # have to write "or die" on everything.
    use autodie;
    
    open my $fh, "whatever-your-file-is";
    while( my $line = <$fh> ) {
        chomp $line;
        mkdir $line;
    }
    

    If the file contains lines like some/sub/directory you'll want to use mkpath from File::Path instead of mkdir.