title: Transferring & Deleting Files From SFTP Using SFTP Foreign Module
body: <p>My requirement is to transfer files and folders from SFTP remote location to unix location. I am new to perl and shell scripting, and this has been very confusing. I tried using rget command from sftp foreign as shown below. But it doesn't work and it isn't getting transferred. How do I delete the files and folders after copying them from the sftp server?</p>
  
  <pre><code>use Net::SFTP::Foreign;
  
  my $host       = "sftp.elsevier.com";
  my $remote_dir = "sample/host";
  my $localdir = "sample/local";
  my $username   = "username";
  my $password   = "password";
  my $debug      = 0;
  
  $sftp = Net::SFTP::Foreign-&gt;new($host, timeout =&gt; 240,user =&gt; $username, password =&gt; $password) or $newerr = 1;
  push @ERRORS, "Can't sftp to $host: $!\n" if $newerr;
  myerr() if $newerr;
  print "Connected to $host\n";
  
  $sftp-&gt;rget($remote_dir, $localdir) or $newerr = 1;
  push @ERRORS, "Cant tranfer\n" if $newerr;
  myerr() if $newerr;
  $sftp-&gt;disconnect if $newerr;
  print "Files are transferred successfully\n";
  
  #Deleting files
  
  $sftp-&gt;setcwd($remote_dir) or $newerr = 1;
  push @ERRORS, "Can't cd $!\n" if $newerr;
  myerr()    if $newerr;
  $sftp-&gt;disconnect if $newerr;
  
  my $files = $sftp-&gt;ls or $newerr = 1;
  push @ERRORS, "Can't get file list $!\n" if $newerr;
  myerr() if $newerr;
  
  foreach (@$files){
  $sftp-&gt;remove($_) or $newerr = 1;
  push @ERRORS, "Cant delete\n" if $newerr;
  myerr() if $newerr;
  
  print "Deleted files successfully\n";
  
  #}
  $sftp-&gt;disconnect;
  
  sub myerr {
      print "Error: \n";
      print @ERRORS;
      exit 0;
  }
  </code></pre>
  
  <p>Inside the SFTP location - sample/host, I have many folders and files which all need to be copied to the local unix server - sample/local and deleted from the remote location.</p>