in reply to Count occurrences and rename words in order

#!/usr/bin/perl -w use strict; $_ = 'doc123/print doc456/read doc789/print doc145/print doc123/read'; my %counts; s|(/\w+)|$1 . ++$counts{$1}|ge; print;

Seems to give the right output for the sample you gave.

--
<http://www.dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^2: Count occurrences and rename words in order
by flounder99 (Friar) on Sep 18, 2002 at 16:28 UTC
    If the data is in a file (say logfile) a one-liner could be used.
    $ perl -pe 's|(/\w+)|$1 . ++$counts{$1}|ge' logfile>countedlogfile $ cat logfile doc123/print doc456/read doc789/print doc145/print doc123/read $ cat countedlogfile doc123/print1 doc456/read1 doc789/print2 doc145/print3 doc123/read2

    --

    flounder

      Yeah, that works. It's unclear what the original poster wanted to do for multiple lines. I assumed that the counts should be cleared. In which case you'd do something like this:

      $ perl -pe '%counts=();s|(/\w+)|$1 . ++$counts{$1}|ge' logfile>counted +logfile
      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg

Re: Re: Count occurrences and rename words in order
by Anonymous Monk on Sep 18, 2002 at 16:46 UTC
    Thanks Monk
    It works for the first line of the text file, but the events on the rest of the file continue the numeration from the first line, and the event from each line should be independent.
    But I will it use to count the events in a whole document!!:)

      You just need to reset %count to be empty before processing each line.

      while (<INPUT>) { my %counts; s|(/\w+)|$1 . ++$counts{$1}|ge; print OUTPUT; }
      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg