0

one simple question, but I couldn't find the solution anywhere. I have a text file which consists of students, lets say, and looks like this:

1 bob smedley 4
2 rob nielsen 7
3 sol connie 9
4 jon sidney 18

Then I have a structure Student, that looks like this:

struct Student => {ID => '$', name  => '$', surname => '$', points => '$',};

I loaded this text file into an array using: @stud = <inFILE>;

And now I want to load each row from my @stud into an array of Student structures. Let's call it my @students; so that for example, my first structure looks like this:

id = 1;
name = bob;
surname = smedley;
points = 4;

And do that for every row in @stud. Alternatively, I could load those structures directly from file, but I was thinking it might be easier using temp array @stud.

1 Answer 1

4

You do not need to slurp the file into an array. You can process it line by line:

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

use Class::Struct;
struct Student => {ID => '$', name  => '$', surname => '$', points => '$',};

my @students;

while (<>) {
    my ($id, $name, $surname, $points) = split;
    my $s = Student->new;
    $s->ID($id);
    $s->name($name);
    $s->surname($surname);
    $s->points($points);
    push @students, $s;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Whizzil: Remove the prototypes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.