Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^4: I'm having a strange bug with basic file input. I'm a total newb.

by Crackers2 (Parson)
on Dec 05, 2008 at 11:03 UTC ( [id://728257]=note: print w/replies, xml ) Need Help??


in reply to Re^3: I'm having a strange bug with basic file input. I'm a total newb.
in thread I'm having a strange bug with basic file input. I'm a total newb.

Or just drop the read calls altogether and do something like:
$line=<INPUT>; $studentname = substr($line,0,20); $test1 = substr($line,21,3); ...

(Though I'm sure a few monks can come up with an unpack solution or a module that handles fixed-width fields)

Replies are listed 'Best First'.
Re^5: I'm having a strange bug with basic file input. I'm a total newb.
by holli (Abbot) on Dec 05, 2008 at 11:46 UTC
    Though I'm sure a few monks can come up with an unpack solution
    Here you are =)
    use warnings; use strict; use List::Util qw(sum); my $studnum = 0; my $totavg = 0; while (<DATA>) { my ($name, @tests) = unpack ("A20A3A3A3A3", $_); last if $name eq "END"; my $avg = sum(@tests)/4; $totavg += $avg; $studnum++; printf("%-24.20s %6.2f\n", $name, $avg); } $totavg /= $studnum; printf ("\n\n%-24.22s %6.2f\n", $studnum, $totavg); print "Program completed Successfully."; exit 0; __DATA__ Tom Thumb 100096093098 Mickey Mouse 088068095086 Minnie Mouse 078056088098 Donald Duck 098096078100 Tad Pole 100100100100 Mack Aroni 095067089098 Cassie Role 082045088079 Mary Martin 085096093088 Mickey Mantle 088063095086 Darryl Strawberry 078056098098 Donald Trump 098086078100 Steve Young 100078097093 Mack Truck 095067099098 Mel Gibson 082075088079 END 000000000000


    holli, /regexed monk/
      Wow...I wish I could do that. :P

      I would so use it, but my teacher would get suspicious. Thanks a lot. :)
Re^5: I'm having a strange bug with basic file input. I'm a total newb.
by ikegami (Patriarch) on Dec 05, 2008 at 11:36 UTC
    unpack is better with fixed-width records
    my ( $name, @tests ) = unpack( 'A20 A3 A3 A3 A3', $line );

    With 5.8.0+, you can even do

    my ( $name, @tests ) = unpack( 'A20 (A3)4', $line );

    or

    my ( $name, @tests ) = unpack( 'A20 (A3)*', $line );

    Update: Heh, I hadn't noticed the bit about unpack at the bottom before posting.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://728257]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (9)
As of 2024-04-18 20:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found