in reply to Delete Duplicate Entry in a text file

update:

I tried this code:

my $lastrow = ""; while (my $line == "fail.txt") { $line =~ /(.*?)\n/; $line = $1; if ($line ne $lastrow) { print $line, "\n"; $lastrow = $line; } }

but didnt processed anything it showed blinking underscore for so long, I think it hangs..

Replies are listed 'Best First'.
Re^2: Delete Duplicate Entry in a text file
by Kenosis (Priest) on Jun 20, 2012 at 04:33 UTC

    Nice work, astronogun! However, there were just a couple of issues...

    Did you really mean my $line == "fail.txt"? You used == instead of the assignment = and it needs to be done on a file handle: my $line = <$fh>

    Without having changed your code too much, try the following:

    use Modern::Perl; my $lastrow = ""; open my $fh, '<', 'fail.txt' or die $!; while (my $line = <$fh>) { $line =~ s/\n//g; next if !$line; if ($line ne $lastrow) { print $line, "\n\n"; $lastrow = $line; } } close $fh;

    Output:

    hostname1.com Gateway FAIL hostname2.com Gateway FAIL
      Without having changed your code too much

      It could stand a bit more changing though.

      $line =~ s/\n//g; next if !$line;
      Why use s/// and why the /g if you do? If you are going to do it, chomp $line; is preferable. Now what if the line is "0\n"? Zero is false. Contrived? Okay... then what if the line contains some whitespace before the newline? Whitespace is true. Checking for the truth of !$line isn't really what you mean. You want to skip $line unless it contains a non-whitespace character so just say what you mean:
      next unless $line =~ /\S/;
      No need to change the line and no need to re-append the newline later.

      -sauoq
      "My two cents aren't worth a dime.";

        Thank you for your thoughts. My intent was to produce the OP's requested output w/o doing too much to the original code for the sake of a differentiated learning experience.

        I tried your suggestions as follows on the OP's data set:

        use Modern::Perl; my $lastrow = ""; open my $fh, '<', 'fail.txt' or die $!; while (my $line = <$fh>) { next unless $line =~ /\S/; if ($line ne $lastrow) { print $line; $lastrow = $line; } } close $fh;

        Output:

        hostname1.com Gateway FAIL hostname2.com Gateway FAIL Gateway FAIL

        Unless I've misunderstood your re-coding suggestions, they do not produce the OP's desired outcome. (Using say instead of print produces the desired line spacing, but the last string is repeated.)

      Hi Kenosis

      Great it worked thank you very much for modifying the script :)

      Regarding the "=" sign I used the "==" sign because on my perl editor when I hovered my mouse on that line it said that it should be "==" not "=" (I'm using Komodo Edit 7.0)