Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having problem splitting a sting around the newline character

Tags:

io

newline

perl

Here is another one of these weird things. I have this code and a 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:

Use of uninitialized value in print at test.pl line 15.

Did anyone encounter a similar problem in the past?

like image 439
masterial Avatar asked Sep 06 '25 03:09

masterial


1 Answers

split takes a regex (I believe your string is coerced into a 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];
like image 58
cam Avatar answered Sep 09 '25 23:09

cam