Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to catch multiple occurence in single line

Status
Not open for further replies.

Zoom1234

Programmer
Oct 30, 2003
116
BE
I have following data
Code:
ABCXYCZ
DEGCPYCJ

I want every character after C, to be pushed into an array.
But when i write,
Code:
my @arr = () ;
open file 
while ( <FH> ) {
 if ( $_ =~ /C(.)/ ) {
    push(@arr, $1) ;
 } 
}
it only recognize first occurence of C in single line and does not consider any more occurences.
It will add only X and P and NOT Z and J.

How do i acheive that?

 
Try this:

Code:
my @arr = () ;
open file 
while ( <FH> ) {
 if ( $_ =~ g/C(.)/ ) {
    push(@arr, $1) ;
 } 
}


If at first you don't succeed, don't try skydiving.
 
Hi netman4u,
Did you mean
Code:
if ( $_ =~ /C(.)/g ) {
Even i tried that, I could not get required result.
 
What about this? (untested).
Code:
while ( $_ =~ /C(.)/g ) {
 
Sorry Zoom. Should stick to ASKING questions!

[blush]

If at first you don't succeed, don't try skydiving.
 

Your code seems to be assuming only one instance on each line of input. How about something like:

open ( <FIL>, "<", "filename.ext" );
$data = <FIL>;
close ( FIL );

$data =~ s/\s//gs;
@array = split ( /C/, $data );
for ( @array ) {
push ( @result, /^(.)/ );
}

...except that this adds the first character regardless. Have you tried playing around with grep?
 
Hi AMiSM,
Instead of using split, can't it be done by using regex?



 
Yes. The code I posted does indeed give the correct output. I've even gone and tested it for you now ;-)
 
ishnid ,

I must be doing something wrong.

Following is my code
Code:
my @arr = () ;
while(<DATA>) {
        if ( $_ =~ /C(.)/g ) {
                push(@arr, $1) ;
        }
}
print "@arr\n" ;


__DATA__
ABCXYCZ
DEGCPYCJ

I get output as
X P
while i am expecting output to be
X Z P J

Any ideas?
 
See my post above (third reply). Change the `if' to a `while' and there you go.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top