How do I change my directory back?

V

Victor

1- create dir dd1
2- chdir to dd1
3- do things
4- chdir back to original dir
5- create dir dd2
6- chdir to dd2
7- do things

But, chdir to prev dir does not happen at step 4.
The second dir at step 5 is actually gets created
in dir dd1.

Here is the part of code:

$mydir = `pwd`;
&s1;
&s2;

sub s1 {
system "mkdir dd1";
chdir "dd1";
.....
.....
chdir $mydir;

}

sub s2 {
system "mkdir dd2";
chdir "dd2";
.....
.....
chdir $mydir;
}

Any help will be highly appreciated.
Thanks,
-V
 
E

Eric Schwartz

$mydir = `pwd`;

use Cwd;
my $mydir = getcwd;
&s1;
&s2;

Don't call subs with & unless you know why you're doing it. perldoc
perlsub to find out more.
sub s1 {
system "mkdir dd1";
chdir "dd1";
....
....
chdir $mydir;

}

You really should ask Perl for all the help it can give you first.
use strict; and use warnings; won't help this problem, but they will
likely help you find and fix other problems early on.

In this case, however, you're calling chdir(), you know it's failing,
and you're not checking the result of the call to find out why.
perldoc -f chdir tells you:

It returns true upon success, false otherwise.
See the example under "die".

The examples (from 'perldoc -f die') are pretty clear, I think:

Equivalent examples:

die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"

I personally prefer the second form, but have no good reason for doing
so.
Any help will be highly appreciated.

c.l.p.m helps those best who help themselves. :)

-=Eric
 
T

Tad McClellan

Victor said:
1- create dir dd1
2- chdir to dd1
3- do things
4- chdir back to original dir
5- create dir dd2
6- chdir to dd2
7- do things

But, chdir to prev dir does not happen at step 4.

chdir $mydir;
Any help will be highly appreciated.


Ask perl to help you by checking the return value from chdir():

chdir $mydir or die "could not cd to '$mydir' $!";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top