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

Whats the best way to split a string of uknown length on whitespace, and populate an array?
while (<INPUT>) { my $line = $_; @push @lineinfo, split $line; my $length = @lineinfo; print "LEN: $length\n"; @lineinfo = (); }
This doesn't work

Any idea why not?

Replies are listed 'Best First'.
Re: String parse
by tall_man (Parson) on Feb 01, 2003 at 04:07 UTC
    That "@push" is a typo. (Use strict and you will get messages about such things.) It should be the command push, but you don't need it anyway in this case. Here's a shorter version:
    use strict; while (<INPUT>) { # $_ is implied by default. my @lineinfo = split; print "LEN: ",scalar(@lineinfo),"\n"; }
Re: String parse
by PodMaster (Abbot) on Feb 01, 2003 at 03:58 UTC
    Because it does not compile (you can't make stuff up).
    push @lineinfo, split $line;


    MJD says you can't just make shit up and expect the computer to know what you mean, retardo!
    ** The Third rule of perl club is a statement of fact: pod is sexy.

Re: String parse
by thezip (Vicar) on Feb 01, 2003 at 04:19 UTC

    I think that what you're trying to do is to read a file line by line, split each line on spaces, and then do something with each resulting array.

    I'll assume that you have a smallish file, and want to slurp the entire file...

    #!/perl/bin/perl use strict; use warnings; use Data::Dumper; my($ifh, @all_lines); open($ifh, "text.txt") or die "Could not read file.\n"; while (<$ifh>) { # split's default delimiter is whitespace, and if # no expression is supplied, it splits $_ my @lineinfo = split; for (@lineinfo) { # print each element on it's own line print $_, "\n"; } print "\n"; print sprintf qq(Line %d has %d elements.\n\n), $., $#lineinfo + 1; # push a reference to each array into an array push (@all_lines, \@lineinfo); } close $ifh; # Dump it all out... print Dumper(\@all_lines); __DATA__ one two three four five six seven eight nine ten eleven twelve

    Where do you want *them* to go today?
Re: String parse
by OM_Zen (Scribe) on Feb 01, 2003 at 04:53 UTC
    Hi ,

    use strict; while(<INPUT>){ local $/; my $line = $_; ########@push @lineinfo, split $line; ###### The @push .... is not a compiling code my @lineinfo = split(' ',$line); ########## @lineinfo = () ; I have less cluesss on what you are do +ing ######### You have to use strict; ######### learn about split,push commands and perldoc perlop ######### perldoc split ######### perldoc push ######### perldoc perlop ######### abotu strict module too
      You have to use strict

      Well no, you don't have to use strict. But it's recommended, to make your life easier. :-)

      ibanix

      $ echo '$0 & $0 &' > foo; chmod a+x foo; foo;