Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Either or question

Status
Not open for further replies.

columb

IS-IT--Management
Joined
Feb 5, 2004
Messages
1,231
Location
EU
This ought to be so easy that I'm probably looking in entirely the wrong direction. The code has to copy files into two directories, each with a slightly different list of files. I'm controlling this with two hashes %uf and %nf where the existence of a hash entry implies that the file is required and that entry is set to 0 or 1 depending on whether the file has already been copied. Here's a code snippet
Code:
  exists $nf{$fname} && $nf{$fname} == 0 and do
    {
    print "Processing $fname in $n_dir\n";
    -f "$u_dir/$fname" and do
      { print "Linking $fname\n"; system "ln $u_dir/$fname $n_dir/$fname"; }
        or  do
      { print "Copying $fname\n"; system "cp $line $n_dir/$fname"; };
      $nf{$fname} = 1;
    };
The problem appears to be that 'system' returns 0 when the command works successfully and that is making it go down the or leg. i.e. it finds the file in $u_dir and links it but then proceeds to copy it as well.

Please point me in the right direction. Thanks

Ceci n'est pas une signature
Columb Healy
 
You're right. system will return 0 if successful. You could use Perl functions rather than calls to "system" to perform those tasks. You could use the builtin "link" function to replace the call to "ln", and the standard File::Copy module includes a "cp" function that will replace your call to the external "cp" via system. Both of those return true on success so you shouldn't have to modify the logic in your code.

 
Many thanks for this ishnid - works a treat now. The next step is to replace the system call to 'find' with File::Find.

Ceci n'est pas une signature
Columb Healy
 
I think the code could benefit from better flow control using if/elsif/else blocks. 'and do/or do' seems like ancient perl syntax. Something like:

Code:
use File::Copy;
if( exists $nf{$fname} && $nf{$fname} == 0 ) {
    print "Processing $fname in $n_dir\n";
    if (-f "$u_dir/$fname") {
       print "Linking $fname\n";
       link ("$u_dir/$fname", "$n_dir/$fname") or die "Link failed: $!";
    }
    else {
       print "Copying $fname\n";
       copy($line, "$n_dir/$fname") or die "Copy failed: $!";
    }
    $nf{$fname} = 1;
}

- Kevin, perl coder unexceptional!
 
Thanks Kevin. As a recent perl convert any advice on syntax is gratefully received.

Ceci n'est pas une signature
Columb Healy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top