dbnoob
dbnoob

Reputation: 71

Perl script returning 0 when a file is read

Im just trying to copy a file to a different directory before I process it. Here is the code:

use File::stat;
use File::Copy;
use LWP::UserAgent;
use strict;
use warnings;
use Data::Dumper;
use Cwd qw(getcwd);


my $dir = "\\folder\\music";
my $dir1 = "c:\\temp";

opendir(my $dh, $dir) or die "Cant open directory : $!\n";
#my @list = readdir($dh)

my @files = map { [ stat "$dir/$_", $_ ] }
grep( /Shakira.*.mp3$/, readdir( $dh ) );
closedir($dh);
sub rev_by_date 
{
   $b->[0]->ctime <=> $a->[0]->ctime 
}
my @sorted_files = sort rev_by_date @files;
my @newest = @{$sorted_files[0]};
my $name = pop(@newest);
print "Name: $name\n";
#**********************
#Upto here is working fine



my $new;

open OLD,"<",$name or die "cannot open $old: $!";

from here the problem starts

open(NEW, "> $new") or die "can't open $new: $!"; 
while () 
{ 

print NEW $_ or die "can't write $new: $!";
 } 
close(OLD) or die "can't close $old: $!"; 
close(NEW) or die "can't close $new: $!"; 

The error im getting is : cannot open Shakira - Try Everything (Official Video).mp3: No such file or directory at copy.pl line 49.

when Im chomping the filename, like my $oldfile = chomp($name); then the error is : Name: Shakira - Try Everything (Official Video).mp3 old file is 0 cannot open 0: No such file or directory at copy.pl line 49.

Any idea?

Upvotes: 0

Views: 143

Answers (1)

choroba
choroba

Reputation: 241918

chomp changes its argument in place and returns the number of removed characters. So the correct usage is

chomp(my $oldfile = $name);

Also, you probably wanted

while (<OLD>) {

instead of

while () {

which just loops infinitely.

Moreover, you correctly prepend $dir/ to a filename in the stat call, but you shold do so everywhere.

Upvotes: 3

Related Questions