in reply to tracking words in lines

Try this:

use strict; use warnings; while ( my $line = <DATA> ) { next unless $line =~ /\band\b/; chomp $line; my @words = split /\s+/, $line; my $location = 0; my @locations; foreach ( @words ) { $location++; push @locations, $location if m/\band\b/; } local $" = ", "; print "Line $.: 'and' appears as word @locations.\n"; } __DATA__ This is a test and a test and a test.

Dave

Replies are listed 'Best First'.
Re^2: tracking words in lines
by sulfericacid (Deacon) on Nov 12, 2004 at 19:22 UTC
    I like your code for this one. Just a question though regarding your regex.

    Is your m/\band\b/ better than my method of m/^and$/? Wouldn't they be doing exactly the same thing?



    "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

    sulfericacid

      There is a difference. Consider the following:

      son-and-law I can't promise anything (and never will). People should carpool--and in some cases they do--since it saves gas.

      m/^and$/ will miss the 'and' in these cases, even though it is there. I don't know whether the OP wants that or not, as he didn't really specify edge cases. If such edge cases should be disallowed, my code would need a minor modification so as to not attempt to print anything if @locations is empty.


      Dave

        Ahh, okay. I had a feeling it would matching something like "and!" or "and?" where mine would fail miserably.

        Thanks.



        "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

        sulfericacid