Search code examples
regexperlperlscript

How to read string from a file and to split them to different array?


I am struggling with this part for my college exercise... I need to read string from a file and put them into different variable... Team, kindly review and please reply in your free moment...

Input File: (test_ts.txt)

Test1--12:45
Test2--1:30

Script:

use strict;
use warnings;

my $filename = "test_ts.txt";
my @name = ();
my @hrs=();
my @mins=();

open(my $fh, $filename)
  or die "Could not open file '$filename' $!";

while (my $row = <$fh>) {
  chomp $row;
  push(@name, $row);
  print "$row\n";
}

Output:

Test1--12:45
Test2--1:30

Expected output:

Test1
Test2

*(Array should have the below values
name[0]=Test1
name[1]=Test2
hrs[0]=12
hrs[1]=1
mins[0]=45
mins[1]=30)*

Tried using Split:

while (my $row = <$fh>) {
  chomp $row;
  $row=split('--',$row);
  print $row;
  $row=split(':',$row);
  print $row;
  push(@name, $row);
  print "$row\n";
}

Output which i got after trying split:

211
211

Solution

  • split returns a list; when you use it in a scalar context like $row = split(..., $row); then:

    1. You only get the number of elements of the array assigned.
    2. You destroy your $row in the input.

    You need something more like:

    while (my $row = <$fh>)
    {
        chomp $row;
        my @bits = split /[-:]+/, $row;
        print "@bits\n";
        push(@name, $bits[0]);
        …other pushes…
        print "$row\n";
    }
    

    You will need to learn about scalar and array context sooner or later. In the mean time, assign the result of split to an array.