#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    31
    Rep Power
    2

    String matching and break in perl


    Hi All,

    I am reading one file and split them with white space and storing all in an array called @array.

    Now I want to compare each member of an array, if any of the member is "DevShed_Forum));" then replace it with "DevForum);" and come out of the loop.

    ########### MY CODE ###################
    while($line=<FILE>) #Reading individual lines from the file
    {
    $line=~ s{#.*}{}; #Removing commented lines
    @array=();
    @array= split / /,$line;
    $j = (@array);

    #Now I want to compare.
    for ($i=0; $i<$j, $i++)
    {
    if ($array[$i] eq "DevShed_Forum));")
    {
    $array[$i] = "Dev_Forum);"
    ##### Now I want to come out of this loop.
    }
    }
    }
    ###########################################################
    Here the issues are:

    1) My this comparison logic is not working (I guess because of the two closing brackets "));" in my string, which matches with my if condition opening bracket "(")

    2) I dont know how to come out of the loop if the string matches.


    If possible Please help me.
  2. #2
  3. !~ /m$/
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    May 2004
    Location
    Reno, NV
    Posts
    4,254
    Rep Power
    1810
    The closing brackets in the string are fine. The usual cause of strings not matching is because of failure to remove the newline character from the end of the original string.

    The 'last' keyword will exit a for loop:

    Code:
    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my $file = 'test.txt';
    open my $fh, '<', $file or die "Can't open $file: $!";
    
    while (<$fh>) {
    	chomp;
    	s/#.*//;
    	my @array= split / /;
    	
    	foreach my $word (@array) {
    		if ($word eq 'DevShed_Forum));') {
    			$word = 'Dev_Forum);';
    			last;
    		}
    	}
    	
    	print "@array\n";
    }

    Comments on this post

    • bonny1989 agrees : Thanks. :)

IMN logo majestic logo threadwatch logo seochat tools logo