user3001499
user3001499

Reputation: 811

Perl: Rename all files in a directory

So I am brand new to Perl and this is my first program (excluding a few basic tutorials to get to grips with very basic syntax)

What I want to do is rename all files within a specified directory to "File 1", "File 2", "File 3" etc

This is the code I have got so far:

use 5.16.3;
use strict;

print "Enter Directory: ";
my $directoryPath = <>;
chdir('$directoryPath') or die "Cant chdir to $directoryPath$!";

@files = readdir(DIR); #Array of file names
closedir(DIR);

my $i = 1; #counting integer for file names
my $j = 0; #counting integer for array values
my $fileName = File;

for (@files)
{
    rename (@files[j], $fileName + i) or die "Cant rename file @files[j]$!";
    i++;
    j++;
}

chdir; #return to home directory

I have a number of issues:

1: Whenever I try to change directory I get the 'or die' message. I am wondering if this is to do with the working directory I start from, do I need to go up to the C: directory by doing something like '..\' before traversing down through a different directory path?

2: Error message 'Bareword "File" not allowed while "strict subs" in use'

3: Same as point 2. but for "i" and for "j"

4: Error message 'Global symbol "@files" requires explicit package name'

Note: I can obviously only get error one if I comment out everything after line else the program won't compile.

Upvotes: 0

Views: 977

Answers (2)

TLP
TLP

Reputation: 67900

  1. No. You probably need to chomp($directoryPath) first to remove the newline, though. And remove the single quotes, since they do not allow interpolation. You never need to quote a single variable like that.
  2. File should be "File". Otherwise it is a bareword.
  3. j should be $j, and same for i
  4. You must declare with my @files, just like you did with the other variables.

You should also know that + is not a concatenation operator in Perl. You should use . for that purpose. But you can also just interpolate it in a double quoted string. When referring to a single array element, you should also use the scalar sigil $, and not @:

rename($files[$j], "$fileName$i") or die ...

You have also forgotten to opendir before you readdir.

You are using a for loop, but not using the iterator value $_, instead using your own counter. You are using two counters where only one is needed. So you might as well do:

for my $i (0 .. @files) {   # @files in scalar context returns its size
    rename($files[$i], $fileName . ($i+1)) or die ...
}

Upvotes: 2

Toto
Toto

Reputation: 91373

  1. Change chdir('$directoryPath') to chdir("$directoryPath") (Double quote for interpreting variable) and chomp it before
  2. File -> "File"
  3. i -> $i
  4. Declare my @files

Upvotes: 0

Related Questions