in reply to Weighted averages

I agree with thanos1983 that it looks like you're searching for some kind of nested data structure. Maybe you can try something and ask us how to improve it, or show us how you might expect the data to look like (but it would help if you understood how nested structures work for that). Anyway, there is a nice idiom to access elements in an array when each position has a special meaning, constant:

use strict; use warnings; use feature qw(say); use constant { STUDENT => 0, FIRST_QUIZ => 1, LAST_QUIZ => 3, FIRST_EXAM => 4, LAST_EXAM => 5, FINAL => 6, }; while (<DATA>) { my @fields = split /,/, $_; say "Student:", $fields[STUDENT]; say "Quizzes:", join ", ", @fields[FIRST_QUIZ..LAST_QUIZ]; say "Exams:", join ", ", @fields[FIRST_EXAM..LAST_EXAM]; say "Final:", $fields[FINAL]; say "-----" } __DATA__ Allen Bailey,90,95,80,98,76,89 Carole Daily,9,9,8,9,7,8 Evan Fairly,50,75,10,82,64,79
Student:Allen Bailey Quizzes:90, 95, 80 Exams:98, 76 Final:89 ----- Student:Carole Daily Quizzes:9, 9, 8 Exams:9, 7 Final:8 ----- Student:Evan Fairly Quizzes:50, 75, 10 Exams:82, 64 Final:79 -----
Here I have used Slices (@ meaning several elements at a time, and a list inside the [ ] rather than a single value, but you can define FIRST_QUIZ, SECOND_QUIZ and so on and access each element one by one if it's simpler to you.

Also in /\w*\s\w*/, the * means 0 or more. So that's "maybe a letter/digit or more, a space, maybe a letter/digit or more", in the end the condition is pretty much only "a space". This might work, but this doesn't look like much of a constraint. Maybe you want + instead of * ?

Replies are listed 'Best First'.
Re^2: Weighted averages
by drose2211 (Sexton) on Jan 25, 2018 at 17:25 UTC

    I feel like this is a stupid question, but what part of the while loop is allowing it to know to start a new group. Student, quize,exam, final. How does it go about starting with student again? In constant student is set to zero, but the second student is in the 7th index and not 0. Maybe I am just not understanding how that works. My second question is about running that through a subroutine. If I wanted to run the quizes through my quiz subrotuine would it be as simple as:

    sub quiz { return (sum(@fields[FIRST_QUIZ..LAST_QUIZ])/ 300) * .10; }

    Ultimately I am trying to find the final grades for each student.

      The data is read line by line. So each new line you get a new iteration of the loop, a new array, which starts at 0 again.

      Using my code and your sub, you could just write: say "Weighted average: ", quiz(@fields[FIRST_QUIZ..LAST_QUIZ]) + exam(@fields[FIRST_EXAM..LAST_EXAM]) + final($fields[FINAL])

        Ah yes, that makes sense. Ok I am going to go and mess around with that a bit. Thanks for the help.