简体   繁体   中英

Matching and printing perl files

I have a large file (lets say File A) and I am wanting to pull certain lines of data from it in perl. An example entry my be as follows.. It would always be 10 points of data and the entries are 5-6 alphanumeric characters long with a : on the end. A line could have more than one entry on it, but \\W+ covers the space in between.

.... 
....
LookupReferences: {
  12V0E:
  24983:
  384KJ:
  48743X:
  52V0E:
  64983:
  784KJ:
  88743X:
  94983:
  1084KJ:
}

I would want that to look like the following entry that i can load elsewhere.

References,12V0E,24983,384KJ,48743X,52V0E,64983,784KJ,88743X,94983,1084KJ

I was reading somewhere about forcing the entire page into an array, but any help here is really appreciated as I have been messing around with it and have not really used any perl in 10 years, so could be classed again as an absolute beginner.

I quite like the range operator for this job.

Eg

while ( <$file_handle> ) {
     if ( m/LookupReferences/ .. /\}/ ) {
           print;
     }
}

(Instead of print you may want to process and concatenate or otherwise push into an array).

I'm not so keen about forcing the whole file into an array, because it's not very efficient when you're looking at larger files.

But if you want to do that, it's as simple as:

my @file = <$filehandle>; 

Following on from comments: As you're trying to reformat it, you can do something like:

my @references; 
while ( <$file_handle> ) {
     if ( m/LookupReferences/ .. /\}/ ) {
           my ( $value ) = ( m/\s*(\w+):/ );
           if ( defined $value ) { push ( @references, $value )  }; 
     }
}

print join ( ",", "References", @references ),"\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM