Search code examples
perlstringfile-read

With Perl, how do I read records from a file with two possible record separators?


Here is what I am trying to do:

I want to read a text file into an array of strings. I want the string to terminate when the file reads in a certain character (mainly ; or |).

For example, the following text

Would you; please
hand me| my coat?

would be put away like this:

$string[0] = 'Would you;';
$string[1] = ' please hand me|';
$string[2] = ' my coat?';

Could I get some help on something like this?


Solution

  • One way is to inject another character, like \n, whenever your special character is found, then split on the \n:

    use warnings;
    use strict;
    use Data::Dumper;
    
    while (<DATA>) {
        chomp;
        s/([;|])/$1\n/g;
        my @string = split /\n/;
        print Dumper(\@string);
    }
    
    __DATA__
    Would you; please hand me| my coat?
    

    Prints out:

    $VAR1 = [
              'Would you;',
              ' please hand me|',
              ' my coat?'
            ];
    

    UPDATE: The original question posed by James showed the input text on a single line, as shown in __DATA__ above. Because the question was poorly formatted, others edited the question, breaking the 1 line into 2. Only James knows whether 1 or 2 lines was intended.