How do I cd into a directory using perl?

前端 未结 3 790
野性不改
野性不改 2021-01-12 15:45

I am trying the following.. system \"cd directoryfolder\" but it fails, also I try system \"exit\" to leave the terminal but it fails.

3条回答
  •  Happy的楠姐
    2021-01-12 16:04

    I always like mention File::chdir for cd-ing. It allows changes to the working directory which are local to the enclosing block.

    As Peder mentions, your script is basically all system calls tied together with Perl. I present a more Perl implementation.

    "wget download.com/download.zip"; 
    system "unzip download.zip" 
    chdir('download') or die "$!"; 
    system "sh install.sh";
    

    becomes:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use LWP::Simple; #provides getstore
    use File::chdir; #provides $CWD variable for manipulating working directory
    use Archive::Extract;
    
    #download
    my $rc = getstore('download.com/download.zip', 'download.zip');
    die "Download error $rc" if ( is_error($rc) );
    
    #create archive object and extract it
    my $archive = Archive::Extract->new( archive => 'download.zip' );
    $archive->extract() or die "Cannot extract file";
    
    {
      #chdir into download directory
      #this action is local to the block (i.e. {})
      local $CWD = 'download';
      system "sh install.sh";
      die "Install error $!" if ($?);
    }
    
    #back to original working directory here
    

    This uses two non-core modules (and Archive::Extract has only been core since Perl v5.9.5) so you may have to install them. Use the cpan utility (or ppm on AS-Perl) to do this.

提交回复
热议问题