I'm not entirely sure I understand the rules by which you want newlines to be added to the output or not. In the following, if you don't want newlines in the output, change the two occurrences of "\n" to " ".

#!/usr/bin/env perl use warnings; use strict; my %data; my $cur_tag; while (<DATA>) { chomp; if ( my ($tag,$line) = /^(X\S+)\s+(.+)$/ ) { $data{$tag} .= "\n" if exists $data{$tag}; $data{$tag} .= $line; $cur_tag = $tag; } elsif ($cur_tag && !/^BEGIN_TAG/) { $data{$cur_tag} .= "\n".$_; } } for my $tag (sort keys %data) { print "$tag: $data{$tag}\n"; } __DATA__ BEGIN_TAG X1 test1 test1 test1 X2 no1 no1 no1 no1 X3 yes1 yes1 yes1 BEGIN_TAG X1 test2 test2 test2 test3 test3 test3 X2 no2 no2 no2 no2 no2 no3 no3 no no3 no3 no4 no4 no4 no4 no4 no4 no4 X3 hi2 hi2 hi2 hi2 hi2 hi2 hi3 hi3 hi3 hi3 hi4 hi4

Output:

X1: test1 test1 test1 test2 test2 test2 test3 test3 test3 X2: no1 no1 no1 no1 no2 no2 no2 no2 no2 no3 no3 no no3 no3 no4 no4 no4 no4 no4 no4 no4 X3: yes1 yes1 yes1 hi2 hi2 hi2 hi2 hi2 hi2 hi3 hi3 hi3 hi3 hi4 hi4

Update: Inverted "\n" vs " ".


In reply to Re^2: Scanning a file and extracting certains values within one or multiple lines by haukex
in thread Scanning a file and extracting certains values within one or multiple lines by Arengin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.