bnghtz

compare_2arrays_item-by-item.pl

Jun 12th, 2014
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.10 KB | None | 0 0
  1. #! /usr/bin/perl
  2. use strict;
  3. use warnings;
  4.  
  5. my @a = qw(a f g h s t);
  6. my @b = qw(a f g h s t);
  7. my @c = qw(a f g h s x x);
  8. my @d = qw(a f g h s t);
  9.  
  10.  
  11. sub compareArr($$;$)
  12. {
  13.   my ($ar1, $ar2, $max) = @_;
  14.  
  15.   return 1 if $#{$ar1} == -1;
  16.  
  17.   if (defined($max) && (($max > $#{$ar1}) || ($max > $#{$ar2})))
  18.   {
  19.     warn "index '$max' is too big...\n";
  20.     return 0;
  21.   }
  22.  
  23.   $max ||= $#{$ar1};
  24.   my $ret = 0;
  25.  
  26.   if ($#{$ar1} == $#{$ar2} || defined($max))
  27.   {
  28.     $ret = 1;
  29.     for (my $i = 0; $i <= $#{$ar1} && $i <= $max; $i++)
  30.     {
  31.       return 0 if ($ar1->[$i] ne $ar2->[$i]);
  32.     }
  33.   }
  34.  
  35.   return $ret;
  36. }
  37.  
  38.  
  39. print "\@a, \@b:  ";
  40. print compareArr(\@a, \@b) ? 1 : 0;
  41. print "\n";
  42.  
  43. print "\@a, \@c:  ";
  44. print compareArr(\@a, \@c) ? 1 : 0;
  45. print "\n";
  46.  
  47.  
  48. print "\@c, \@d 6:  ";
  49. print compareArr(\@c, \@d, 6) ? 1 : 0;
  50. print "\n";
  51.  
  52. print "\@c, \@d 5:  ";
  53. print compareArr(\@c, \@d, 5) ? 1 : 0;
  54. print "\n";
  55.  
  56. print "\@c, \@d 4:  ";
  57. print compareArr(\@c, \@d, 4) ? 1 : 0;
  58. print "\n";
  59.  
  60. print "\@c, \@d:  ";
  61. print compareArr([@c[0 .. 3]], [@d[0 .. 3]]) ? 1 : 0;
  62. print "\n";
Advertisement
Add Comment
Please, Sign In to add comment