Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- #
- # https://www.linux.org.ru/forum/development/12024408
- #
- use strict;
- use warnings;
- my $positions_file = 'positions.txt';
- if ( @ARGV > 0 ) {
- &restore_positions();
- &compare();
- &save_positions();
- } else {
- &print_usage();
- exit 1;
- }
- exit 0;
- {
- my %positions;
- sub restore_positions() {
- -e $positions_file or return;
- open my $fh, "<", $positions_file
- or die "open $positions_file: $!";
- while ( <$fh> ) {
- chomp;
- my ( $file, $pos ) = split /:/;
- $positions{ $file } = $pos;
- }
- close $fh
- or die "close $positions_file: $!";
- }
- sub save_positions() {
- open my $fh, ">", $positions_file
- or die "open $positions_file: $!";
- while ( my ( $file, $pos ) = each %positions ) {
- syswrite $fh, join( ':', $file, $pos ) . "\n";
- }
- close $fh
- or die "close $positions_file: !";
- }
- sub get_position($) {
- my ( $file ) = @_;
- return ( exists $positions{ $file } )
- ? $positions{ $file }
- : 0;
- }
- sub set_position($$) {
- my ( $file, $pos ) = @_;
- $positions{ $file } = $pos;
- }
- }
- sub compare() {
- my @FHS;
- for ( my $filenum = 0; $filenum < @ARGV; $filenum++ ) {
- my $file = $ARGV[ $filenum ];
- open my $fh, "<", $file or die "open $file: $!";
- push @FHS, $fh;
- my $pos = &get_position( $file );
- seek( $fh, $pos, 0 ) or die "seek $file: $!";
- }
- my %uniq;
- IN: while ( my $in = <STDIN> ) {
- if ( exists $uniq{ $in } ) {
- delete $uniq{ $in };
- next;
- }
- for ( my $filenum = 0; $filenum < @ARGV; $filenum++ ) {
- my $file = $ARGV[ $filenum ];
- my $fh = $FHS[ $filenum ];
- my $curpos = 0;
- for ( $curpos = tell( $fh );
- my $line = <$fh>;
- $curpos = tell( $fh ) )
- {
- if ( $line eq $in ) {
- &set_position( $file, $curpos );
- next IN;
- }
- if ( not exists $uniq{ $line } ) {
- $uniq{ $line } = 1;
- }
- }
- &set_position( $file, $curpos );
- }
- print $in;
- }
- }
- sub print_usage {
- print <<'EOF';
- Usage:
- echo urls | xcmp.pl file1 [ file2 file 3 ... fileN ]
- EOF
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement