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

Is there a quick command to take and grab a group of alpha-numerics that each group is seperated by a single blank space and it only spans one line? For example the file would look like:

bob 299 frank 107 ted 300

Thanks

Replies are listed 'Best First'.
RE: parsing a scalar into an Array
by nuance (Hermit) on May 16, 2000 at 04:59 UTC
    Your data looks structured. If you want to relate the name to the number you can use a hash instead of an array:
    my $string = "bob 299 frank 107 ted 300"; my %hash = split /\s+/, $string; foreach (keys %hash) { print "$_, $hash{$_}\n"; }
    or: Since you mentioned that you want to read them from a file, and using an array (becuase your subject asks for it :-) ).
    my $file = "/home/andrew/data.txt"; my @array; open (FOO, $file) or die "can't open $file"; while (<FOO>) { @array = (@array, split /\s+/, $_); }; foreach (@array) { print "$_\n"; };

    Nuance

    Baldrick, you wouldn't see a subtle plan if it painted itself purple and danced naked on top of a harpsichord, singing "Subtle plans are here again!"

RE: parsing a scalar into an Array (or Hash!)
by Alokito (Novice) on May 16, 2000 at 09:25 UTC
    Or even just:

    my @hashes = map {{split}} <>; #Ain't perl neat?
    You could use @hashes in the following way:

    foreach (@hashes) my %hash = %{$_}; foreach (keys %hash) { print "$_ => $hash{$_}\t"; } print "\n"; }
    Also, you can easily do an array of arrays instead:

    my @arrays = map {[split]} <>; # Got it?

    IMHO, people should use list operations (map, foreach, grep) in the right places.

Re: parsing a scalar into an Array
by btrott (Parson) on May 16, 2000 at 03:24 UTC
    Do you mean that you want to split that string into an array, where each elements is one of those substrings ("bob", "299", etc.)?

    If so, use split:

    my $string = "bob 299 frank 107 ted 300"; my @array = split /\s+/, $string;
    If that's not what you're asking, could you be more specific?
      Cool these work. Thanks a million you guys!!!
Re: parsing a scalar into an Array
by Anonymous Monk on May 16, 2000 at 05:25 UTC
    sounds like you want the alpha-numeric groups retained...
    my $string = "bob 299 frank 107 ted 300"; my @array = split /\s+/, $string; for ($i=0;$i<@array;$i++) { $newarray{$array[$i]} = $array[($i + 1)]; $i++; } foreach (keys %newarray) { print "key $_\n $newarray{$_}\n"; }