Having a problem breaking a sting around a newline

Here is another one of these strange things. I have this code and file.

use strict;
use warnings;

my $file = "test.txt";
my @arr; 

open (LOGFILE, $file);
while (my $line = <LOGFILE>)     
{ 
    #print $line;
    @arr = split("\n", $line);
}   
close LOGFILE;

print $arr[1];

test.txt contains

\ ntest1 \ ntest2 \ ntest3

Here is the error I get:

Using an uninitialized value in print with test.pl line 15.

Has anyone encountered a similar problem in the past?

+3
source share
2 answers

splitaccepts regex (I believe your string is forced into regex) Maybe something like split(/\\n/, $line)?

 use strict;
 use warnings;

 my $file = "test.txt";
 my @arr;

 open (LOGFILE, $file);
 while (my $line = <LOGFILE>)
 {
   print $line;
   @arr = split(/\\n/, $line);
 }
 close LOGFILE;

 print $arr[1];
+5
source

You can use:

@arr = split /\Q\n/, $line;
+3
source

Source: https://habr.com/ru/post/1784165/


All Articles