Thiyagu ATR
Thiyagu ATR

Reputation: 2264

find the occurrences of particular string in give string?

hi friends now 'm working in perl i need to check the give string occurence in a set of array using perl!i tried lot but i can't can anybody?

open FILE, "<", "tab_name.txt" or die $!;
my @tabName=<FILE>;
my @all_files= <*>;
foreach my $tab(@tabName){

    $_=$tab;
    my $pgr="PGR Usage";
    if(m/$pgr/)
    {

        for(my $t=0;scalar @all_files;$t++){
            my $file_name='PGR.csv';            
            $_=$all_files[$t];          
            if(m\$file_name\)
            {

                print $file_name;           
            }           
        }

        print "\n$tab\n";   

    }
}

Upvotes: 0

Views: 55

Answers (3)

brian d foy
brian d foy

Reputation: 132822

Aside from the problems you have going through the array, are you looking for substr?

Upvotes: 0

user1919238
user1919238

Reputation:

Here is a problem:

for(my $t=0;scalar @all_files;$t++){

The second part of the for loop needs to be a condition, such as:

for(my $t=0;$t < @all_files;$t++){

Your code as written will never end.

However, this is much better:

foreach (@all_files){

In addition, you have a problem with your regex. A variable in a regex is treated as a regular expression. . is a special character matching anything. Thus, your code would match PGR.csv, but also PGRacsv, etc. And it would also match filenames where that is a part of the name, such as FOO_PGR.csvblah. To solve this:

  • Use quote literal (\Q...\E) to make sure the filename is treated literally.
  • Use anchors to match the beginning and end of the string (^, $).

Also, backslashes are valid, but they are a strange character to use.

The corrected regex looks like this:

   m/^\Q$file_name\E$/

Also, you should put this at the top of every script you write:

use warnings;
use strict;

Upvotes: 1

Toto
Toto

Reputation: 91430

This line :

for(my $t=0;scalar @all_files;$t++){

produces an infinite loop, you'd better use:

for(my $t=0;$t < @all_files;$t++){

Upvotes: 0

Related Questions