PDA

View Full Version : -d File test operator


KumaSan
05-27-2002, 11:45 PM
Okay, as part of my attempt at learning perl, I'm writing small program that will move my ogg's from my old hard drive (mounted on /mnt/mp3) to my new one (mounted at /mp3). As a complete newbie, I'm having trouble with even this small task. Here's the relevant code:


#!/usr/bin/perl -w

use File::Copy;
$dir = $ARGV[0];
$dir2 = $ARGV[1];

foreach (`ls $dir`) {
chomp;
$name = $_;
if (-d $name) {
mkdir "$dir2/$name";
}
else {
copy("$dir/$name", "$dir2/$name");
}
}


As you can see, it's still way unfinished (doesn't go into the subdirectories for one thing...) but I'm having big problems with the -d file test. Nothing matches on this. Is there something wrong with my foreach statement? I know there are easier ways to do this (cp at a command line comes to mind) but since I just started learning perl, I need to practice it.

Anyway, thanks in advance for the help. Be gentle, I've only been coding for about 2 weeks.

syam
07-06-2002, 10:04 PM
You have been coding only two weeks -- it is more important that
you learn how to code well than get this program right. Afterall,
you are not accomplishing anything that "cp -r" does not already
do.

Try putting a lot of print statements in your code. Like this

--> print "Trying to check if $name is a directory\n";
if(-d $name)
{
...
}

etc. You will soon find out what is wrong with the test.

Or change the way you write the script. For instance, write it
as follows

my $source = "$dir/$name";
my $target = "$dir2/$name";

and rewrite the rest of the code to not use $name. You will soon
find out why it is wrong. Try it and let me know.

l2kashe
08-21-2002, 04:36 PM
I had issues earlier on with the -(d|f|x) flags... The issue is always the variable is not quoted and not referenced absolutely...

Ie I run the script from my home dir with contents like

code docs images blah baz

the script might work on say /var/tmp

$file = foobar
so if I test (-d "$file") perl doesnt find foobar in the directory I ran it in hence the test fails..

reference the path absolutely and quote it

$base = "/var/tmp";
$file = 'foobar';

if (-d "$base/$file")

This will work..