Problem Splitting Text String

Joined
Dec 9, 2022
Messages
6
Reaction score
0
I have a text file with 240 records separated by "zz". I want to split the file into an array so that each record is in an array slot. Here is the code I am experimenting with.

#!/usr/bin/env perl
use strict;
use warnings;

open(my $configfile, "<", 'PoliceLog.txt') or die "$!";

my @configdata = split('zz',<$configfile>);
print "$configdata[0]\n";
print "$configdata[1]\n";
print "$configdata[2]\n";

close $configfile;

The print "$configdata[0]\n"; command prints the first record correctly. The 2nd and 3rd print commands do not print a record and cause the following error reports.

Use of uninitialized value $configdata[1] in concatenation (.) or string at TestC.pl line 10, <$configfile> line 1.
Use of uninitialized value $configdata[2] in concatenation (.) or string at TestC.pl line 11, <$configfile> line 1.

Any help is appreciated.
 
Joined
Jan 8, 2023
Messages
27
Reaction score
2
You should use the chomp function to remove the newline character that is appended to each element in the array when you use <$configfile> to read the entire file.



Perl:
open(my $configfile, "<", 'PoliceLog.txt') or die "$!";
my $file_data = <$configfile>;
chomp($file_data);
my @configdata = split('zz', $file_data);
print "$configdata[0]\n";
print "$configdata[1]\n";
print "$configdata[2]\n";
close $configfile;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,922
Messages
2,570,047
Members
46,473
Latest member
DaveBrowde

Latest Threads

Top