Getting Info from Array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kriz4321
    New Member
    • Jan 2007
    • 48

    Getting Info from Array

    Hi

    I have a array in which I need to count the number of ocurrence of a particular word
    for eg I need to count no of times a word "test" , "test2" occurs in a array @list.
    (The contents of the array is around 100 lines)

    Code:
    [code=perl]
    open(FH3, "sample.txt ");
    while(<FH3>)
    {
    @array=$_;
    print @array;
    }
    close(FH3);
    my %counts = ();
    for (@array) {
    $counts{$_}++;
    }
    foreach my $keys (keys %counts) {
    print "$keys = $counts{$keys}\ n";
    }

    if($counts{$key s}==1)
    {
    print "$keys = $counts{$keys}\ n";
    }
    [/code]

    I dont want the count for all the words in the array and I need the same only for a given Input word...

    Can you help me in this regard..

    Thanks In Advance
    Last edited by numberwhun; Mar 14 '08, 11:35 AM. Reason: add code tags
  • nithinpes
    Recognized Expert Contributor
    • Dec 2007
    • 410

    #2
    The script you have used is very confusing to understand your objective as per the description. Is that the file sample.txt contains one word per line which you are trying to pass to an array? In that case, you can achieve it without the need of the array:

    Code:
    open(FH3, "sample.txt");
    while(<FH3>)
    {
    chomp;
     $seen{$_} ++ ;
    }
    print "enter the string that you want to search:";
    chomp($str=<STDIN>);
    print "$str occurs $seen{$str} times";
    OR, is that you have text file with multiple lines and you need to split each line into words and push it into array for search? For this you can use:

    Code:
    open(FH3, "cookies.txt");
    while(<FH3>)
    {
    chomp;
     push @a, split(/\s+/,$_); ##split on spaces
    }
    my %seen =();
    $seen{$_}++ foreach(@a);
    print "enter the string that you want to search:";
    chomp($str=<STDIN>);
    
    print "$str was found $seen{$str} times";

    Comment

    • KevinADC
      Recognized Expert Specialist
      • Jan 2007
      • 4092

      #3
      This is just wrong (in the original code):


      Code:
      open(FH3, "sample.txt");
      while(<FH3>)
      {
      @array=$_;
      print @array;
      }
      unless the file only has one line. Otherwise @array will be populated only with the value of the last line of the file.

      Comment

      Working...