开发者

block reading in perl

I need to read one block from开发者_如何学C file and then need to match the particular patterns and get the values for the matched pattern.

> Call report:$VAR1 = {
>           'service_status' => 'DIAL-IN-SEQUENTIAL',
>           'called_id' => '761',
>           'id' => '41298',
>           'redirect_number' => undef,
>           'profile_id' => '137',
>           'not_answered_action' => '0',
>           'call_landed_day' => '1',
>           'call_end_status' => 'CALLER_HANGSUP',
>           'announce_caller_type' => '0',
>           'user_id' => '143',
>           'follow_me_group' => '135',
>           'call_end_time' => '29/11/2010 09:39:57',
>           'findme_id' => '135',
>           'fmsonenumber' => '43902761',
>           'profile_cause' => 'IMMEDIATE_OVERRIDE',
>           'fms_id' => '85dd3b2a-fb6e-11df-a0b0-a1f3d600a5a6',
>           'caller_type' => 'UNKNOWN',
>           'fms_type' => 'FOLLOWME',
>           'profile_desc' => 'office',
>           'caller_id' => '43902761',
>           'call_landed_time' => '29/11/2010 09:39:55'
>         };

From the above block I need to read the block between two { } braces.After that I want to match the particular pattern like service_status and then after matching the service_status pattern should retrieve the value of the service_status as DIAL-IN-SEQUENTIAL.Likewise I need to match the patterns in some of the lines and get the values for that patterns. How can we achieve this?. If anyone know the way to solve this pls give me the solution.

Thanks in advance.


You can process the file so that it became a valid perl module that contains a definition of an array of hashes. Write a filter (or do it with emacs/vim or your favorite editor) to substitute the "Call report:$VAR1 = {" to a statement that pushes the hash into an array, something like "push @all_hashes, {".

Then you can use the module and iterate through the variables as normal perl hashes.


Well, given the constraints my solution is rather ugly, but you can get it as a regexp exercise ( but you can avoid it ):

#!/usr/bin/env perl

use v5.12;
use strict;

open my $fh, '<', 'block.txt';

while ( <$fh> ) {
    if ( /^[^}^{]++$/ .. /^[^}]++$/ ) {
        if ( /(?<='service_status' => )'([^']+)'/ ) { say $1 };
    }
}

Just note how I used the flip-flop operator in the first conditional, and the positive lookbehind in the second conditional.

The first conditional returns true when it finds a line without open or closed curly brace; it keeps returning true until it finds a line with a closed curly brace, when it returns false. With this kind of a filter you get only lines between those with braces.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜