... %i is not remembered from one iteration to the other.
On the contrary,  %i is remembered perhaps too well, being printed entirely for every line (iteration) in the file. Consider the following modification (my file  words2.txt has the same data as given in the OP):
>perl -nle "/(\w*)/; $i{$1}++; print qq{$. $_} for keys %i;" words2.txt 1 foo 2 bar 2 foo 3 bar 3 baz 3 foo 4 bar 4 baz 4 qux 4 foo 5 bar 5 baz 5 qux 5 foo 6 bar 6 baz 6 qux 6 foo 7 bar 7 baz 7 qux 7 foo 8 bar 8 baz 8 qux 8 foo 9 bar 9 baz 9 qux 9 foo
Maybe try something like:
>perl -wMstrict -lne "/(\w+)/; $::i{$1}++; END { print qq{$_ $::i{$_}} for keys %::i } " words2.txt bar 2 baz 2 qux 2 foo 3
Update: removed extraneous  BEGIN { ... } block from second example.

In reply to Re: global vars and one liners by AnomalousMonk
in thread global vars and one liners by punkish

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.