Using chdir($variable_name)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Shridhar Sharma
    New Member
    • Jul 2011
    • 1

    Using chdir($variable_name)

    I have a list of paths in a file => small.txt

    i wish to open that file, copy the path and change my directory to the path collected from small.txt.

    Code:
    open(LIST,"small.txt") or die "Cant open small.txt";
    @arr= <LIST>;
    for($i = 0; $i < @arr; $i++)
    {
    chomp($arr[$i]);
    print "path read from file = $arr[$i]\n";
    #it displays => ms_qu/the/path/written/in/file
    chdir $arr[$i] or die "$1";
    print "After chdir, cwd is = ";
    system("pwd");
    }

    Now im not able to change my directory to the path in $arr[$i]. it shows me the die msg and doesnt change pwd.

    format of path in small.txt:
    xyx/abs/def/ijk

    Although if i write chdir(/abc/def/ijk), it works fine but i want chdir($variable ) where value of variable is collected from small.txt


    PLEASE PLEASE PLEASE HELP ME!!!
    Last edited by numberwhun; Jul 8 '11, 04:46 AM. Reason: Please use code tags around your code!
  • miller
    Recognized Expert Top Contributor
    • Oct 2006
    • 1086

    #2
    There are a few problems with your script, but the biggest one is that your file appears to contain relative paths, but you're assuming they contain absolute paths.

    I also suggest you use the Cwd module to get the current working directory and use better error checking. The below script will probably get you on your way:

    Code:
    use Cwd qw(getcwd abs_path);
    use File::Spec;
    
    use strict;
    use warnings;
    
    my $basedir = abs_path(getcwd);
    
    my $file = 'small.txt';
    open my $fh, $file or die "Can't open $file: $!";
    while (my $relpath = <$fh>) {
    	chomp $relpath;
    	print "path read from file = $relpath\n";
    	
    	my $abspath = File::Spec->catdir($basedir, $relpath);
    
    	chdir $abspath or die "Can't chdir $abspath: $!";
    	print "After chdir, cwd is = ", getcwd, "\n";
    }
    - Miller

    Comment

    Working...