Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Directory Structure.

by shmem (Chancellor)
on Mar 31, 2017 at 13:19 UTC ( #1186621=note: print w/replies, xml ) Need Help??

in reply to Directory Structure.

I tried alot but couldnt able to do that please help me to do that

What you didn't try to do is describing your code to yourself; I'll do that for you:

You create VEHICLES and change into this empty directory. Fine. Inside this directory you create a directory and change into this empty dirctory.

Then, inside this subdirectory, you try to chdir into the directory VEHICLES (which is what the variable $dir holds). This subdirectory doesn't exist in VEHICLES/CARS. Bummer. This part of your code silently fails. Your current working directory stays the same (VEHICLES/CARS).

You iterate to the next element in @files.
You create the next directory, BIKES, and change directory into that. Again, you try to chdir into VEHICLES which doesn't exist.

You end up with


which is your current working directory after the loop ends.

First thing you should do is checking all your operations for success:

$dir = "VEHICLES"; @files = ('CARS', 'BIKES'); mkdir ($dir) or die "can't mkdir $dir: $!"; chdir ($dir) or die "can't chdir to $dir: '$!'"; foreach $file(@files) { mkdir $file or die "(loop) can't mkdir $file: '$!'"; chdir $file or die "(loop) can't chdir to $file: '$!'"; chdir $dir or die "(loop) can't chdir to $dir: '$!'"; }


(loop) can't chdir to VEHICLES: 'No such file or directory' at +line 10.

Aha! there's no such file or directory inside the loop, when you try to chdir to VEHICLES. You realize the two chdir statements inside the loop are bogus and eliminate them:

$dir = "VEHICLES"; @files = ('CARS', 'BIKES'); mkdir ($dir) or die "can't mkdir $dir: $!"; chdir ($dir) or die "can't chdir to $dir: '$!'"; foreach $file(@files) { mkdir $file or die "(loop) can't mkdir $file: '$!'"; }

Then you run your file again. Output now:

can't mkdir VEHICLES: File exists at line 3.

So, you should check for existence before making a directory. See -X for the various file testing operators.

$dir = "VEHICLES"; @files = ('CARS', 'BIKES'); if(not -d $dir) { mkdir ($dir) or die "can't mkdir $dir: $!"; } chdir ($dir) or die "can't chdir to $dir: '$!'"; foreach $file(@files) { if (not -d $file) { mkdir $file or die "(loop) can't mkdir $file: '$!'"; } }

Now your code runs and produces the expected structure:


See chdir, mkdir, not, -X, or, die for more information about the added bits.

perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1186621]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2023-09-25 10:57 GMT
Find Nodes?
    Voting Booth?

    No recent polls found