开发者

how can i fetch the whole word on the basis of index no of that string in perl

开发者 https://www.devze.com 2023-04-10 16:48 出处:网络
I have one string of line like comments:[I#1278327] is related to office communicator.i fixed the bug to declare it null at first time.

I have one string of line like

comments:[I#1278327] is related to office communicator.i fixed the bug to declare it null at first time.

Here I am searching index of I#then I want the wh开发者_高级运维ole word means [I#1278327]. I'm doing it like this:

open(READ1,"<letter.txt");
while(<READ1>)
{
 if(index($_,"I#")!=-1)
 {
  $indexof=index($_,"I#");
  print $indexof,"\n";
  $string=substr($_,$indexof);##i m cutting that string first from index of I# to end then...
  $string=substr($string,0,index($string," "));
  $lengthof=length($string);
  print $lengthof,"\n";
  print $string,"\n";
  print $_,"\n";
 }
}

Is any API is there in perl to find the word length directly after finding the index of I# in that line.


You could do something like:

$indexof=index($_,"I#");
$index2 = index($_,' ',$indexof);
$lengthof = $index2 - $indexof;

However, the bigger issue is you are using Perl as if it were BASIC. A more perlish approach to the task of printing selected lines:

use strict;
use warnings;

open my $read, '<', 'letter.txt'; # safer version of open

LINE:
while (<$read>) {
        print "$1 - $_" if (/(I#.*?) /);
}


I would use a regex instead, a regex will allow you to match a pattern ("I#") and also capture other data from the string:

$_ =~ m/I#(\d+)/;

The line above will match and set $1 to the number.

See perldoc perlre

0

精彩评论

暂无评论...
验证码 换一张
取 消