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

I loaded a file into an array. The file has different parts that i seperated with ":"s. How can I create another array out of the file where each array element contains a different part i seperated with ":"s?
  • Comment on How can i take a file loaded into an array and split it up into different...

Replies are listed 'Best First'.
Re: How can i take a file loaded into an array and split it up into different...
by AltBlue (Chaplain) on Jan 27, 2001 at 05:55 UTC
    my @array; { local $/ = ':'; open INPUT, 'file.txt' or die "blah: $!"; @array = <INPUT>; close INPUT; }

    --
    AltBlue.

      Assuming that the file is also broken w/ newlines (which may very well not be the case) (ie, similar to a CSV), wouldn't just setting $/ mean that at every newline, one of the array elements would contain two fields (specifically, the last one of one line combined w/ the first one of the new line)?

      Blah, I'm probably just making invalid assumptions and should go back to work. :-p

      bbfu

Re: How can i take a file loaded into an array and split it up into different...
by bbfu (Curate) on Jan 27, 2001 at 06:52 UTC
    # @array should hold the info you read from the file, # preferably chomp()'ed my @new_array = (); foreach(@array) { push @new_array, split(':', $_); # Oops. Had @array instead of $_ +. Thanks Beatnik! }
      You mean push @new_array, split(':'); or at least push @new_array, split(':', $_);. Don't ya?

      Greetz
      Beatnik
      ... Quidquid perl dictum sit, altum viditur.

        Oops, I sure do. Thanks, Beatnik!

        What was I thinking?!?  =)

Re: How can i take a file loaded into an array and split it up into different...
by Fastolfe (Vicar) on Jan 27, 2001 at 23:50 UTC
    If you don't mind if the original @array is destroyed:
    $_ = [ split /:/ ] foreach @array;
    Or if you haven't read anything from the filehandle yet:
    my @array = map { chomp; [ split /:/ ] } <DATA>;
Re: How can i take a file loaded into an array and split it up into different...
by ColonelPanic (Friar) on Jan 27, 2001 at 20:22 UTC
    Hmm, sounds like maybe a 2-d data structure us what you want? (This code is untested)
    # @lines is from the file my @bigarray; #the output array foreach (@lines) { my @temp = split ':', $_; push @bigarray, \@temp; }
    now you have an array, @bigarray, where each element is a reference to an array containing all the stuff from one line. To access the inner arrays use syntax like this:
    @{$bigarray[0]}; #access the first inner array ${$bigarray[2]}[3]; #access element 2,3
    the brackets are sometimes unnecessary but I recommend leaving them in for clarity.

    There are many other ways to set/access references. Check out the perllol and perlref manpages.

    When's the last time you used duct tape on a duct? --Larry Wall