How can I read multiple lines of a file into blocks in Perl?

后端 未结 3 743
悲哀的现实
悲哀的现实 2021-01-29 05:57

I have a file which contains the text below.

#L_ENTRY    
#LEX        
#ROOT       
#POS        
#SUBCAT     

        
3条回答
  •  情话喂你
    2021-01-29 06:15

    From this and your succeeding question it's looking like you have the answer but are unaware of it

    As long as your blocks are separated by at least one blank line, you can use Perl's paragraph mode, which will hand you back the text in blocks

    Here's another, different example that I hope you understand. I've created a file called test.txt that contains the data that you posted, and opened it in paragraph mode

    The output is from Data::Dump, which I've used only to demonstrate that the resulting array contains exactly the four strings that you asked for

    Please add a comment to this solution if you need any more explanation

    use strict;
    use warnings 'all';
    use autodie;
    
    my $file = 'test.txt';
    
    my @chunks = do {
        open my $fh, '<', $file;
        local $/ = '';
        <$fh>;
    };
    
    use Data::Dump;
    dd \@chunks;
    

    output

    [
      "#L_ENTRY    \n#LEX        \n#ROOT       \n#POS        \n#SUBCAT     \n#S_LINK           <>\n#BITS    <>\n#WEIGHT      <0.1>\n#SYNONYM     <0>\n\n",
      "#L_ENTRY    \n#LEX        <,>\n#ROOT       <,>\n#POS        \n#SUBCAT     \n#S_LINK           <>\n#BITS    <>\n#WEIGHT      <0.1>\n#SYNONYM     <0>\n\n",
      "#L_ENTRY    \n#LEX        <~>\n#ROOT       <~>\n#POS        \n#SUBCAT     \n#S_LINK           <>\n#BITS    <>\n#WEIGHT      <0.1>\n#SYNONYM     <0>\n\n",
      "#L_ENTRY    \n#LEX        <\@>\n#ROOT       <\@>\n#POS        \n#SUBCAT     \n#S_LINK           <>\n#BITS    <>\n#WEIGHT      <0.1>\n#SYNONYM     <0>\n",
    ]
    

提交回复
热议问题