kevinw has asked for the wisdom of the Perl Monks concerning the following question:

hi, i think i'm using the split() function right, but for some reason, it does not work out how i want....could someone please help? i have
while (<FILE>) { $class= split(/\s+/,$_); print $class; }
basically, FILE contains the following data and i want to get the classes which is the first column.....
Classes categorized by sections: section 1 classC 18 classA 17 classD 16 section2 classE 15 classO 14 classB 16

Replies are listed 'Best First'.
Re: help with split()
by DamnDirtyApe (Curate) on Jul 25, 2002 at 21:36 UTC

    You're close; split returns a list. You want something more like:

    while (<FILE>) { ($class, $enrollment) = split(/\s+/,$_); print $class; }

    Update: Also, the $_ is implied, so you can just write:

    ( $class, $enrollment ) = split /\s+/ ;

    _______________
    D a m n D i r t y A p e
    Home Node | Email
Re: help with split()
by dragonchild (Archbishop) on Jul 25, 2002 at 21:39 UTC
    Context, context, context. split returns an array. When an array is put into scalar context, it gives the number of elements in the array, not the first value.
    while (<FILE>) { ($class) = split /\s+/, $_; print $class, $/; }

    It will discard all the other elements.

    As an aside, check out strict and warnings. They'll help save your life sometime.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: help with split()
by thelenm (Vicar) on Jul 25, 2002 at 21:44 UTC
    The answers so far are right on. Also, if you're only interested in getting the first column, you don't need to use split; you could just use a regex to grab it:
    while (<FILE>) { my ($class) = /(\S+)/; print "$class\n"; }

    -- Mike

    --
    just,my${.02}