copy-if-different.pl revision 326663
1#!/usr/local/bin/perl 2 3use strict; 4 5use Fcntl; 6 7# copy-if-different.pl 8 9# Copy to the destination if the source is not the same as it. 10 11my @filelist; 12 13foreach my $arg (@ARGV) { 14 $arg =~ s|\\|/|g; # compensate for bug/feature in cygwin glob... 15 $arg = qq("$arg") if ($arg =~ /\s/); # compensate for bug in 5.10... 16 foreach (glob $arg) 17 { 18 push @filelist, $_; 19 } 20} 21 22my $fnum = @filelist; 23 24if ($fnum <= 1) 25 { 26 die "Need at least two filenames"; 27 } 28 29my $dest = pop @filelist; 30 31if ($fnum > 2 && ! -d $dest) 32 { 33 die "Destination must be a directory"; 34 } 35 36foreach (@filelist) 37 { 38 my $dfile; 39 if (-d $dest) 40 { 41 $dfile = $_; 42 $dfile =~ s|^.*[/\\]([^/\\]*)$|$1|; 43 $dfile = "$dest/$dfile"; 44 } 45 else 46 { 47 $dfile = $dest; 48 } 49 50 my $buf; 51 if (-f $dfile) 52 { 53 sysopen(IN, $_, O_RDONLY|O_BINARY) || die "Can't Open $_"; 54 sysopen(OUT, $dfile, O_RDONLY|O_BINARY) 55 || die "Can't Open $dfile"; 56 while (sysread IN, $buf, 10240) 57 { 58 my $b2; 59 goto copy if !sysread(OUT, $b2, 10240) || $buf ne $b2; 60 } 61 goto copy if sysread(OUT, $buf, 1); 62 close(IN); 63 close(OUT); 64 print "NOT copying: $_ to $dfile\n"; 65 next; 66 } 67 copy: 68 sysopen(IN, $_, O_RDONLY|O_BINARY) || die "Can't Open $_"; 69 sysopen(OUT, $dfile, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY) 70 || die "Can't Open $dfile"; 71 while (sysread IN, $buf, 10240) 72 { 73 syswrite(OUT, $buf, length($buf)); 74 } 75 close(IN); 76 close(OUT); 77 print "Copying: $_ to $dfile\n"; 78 } 79 80