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

I want to use an array each to get all the column values for every column in a pipe delimited file, please correct the code below with arrays... any help appreciated

... my @colvalues1; my @colvalues2; my @colvalues3; ... push @colvalues1, $allcols[0],':',$allcols[1],"\n"; push @colvalues2, $allcols[0],':',$allcols[2],"\n"; push @colvalues3, $allcols[0],':',$allcols[3],"\n"; ... open my $out1, '>>', "$colnamesxp[1].txt" or die $!; open my $out2, '>>', "$colnamesxp[2].txt" or die $!; open my $out3, '>>', "$colnamesxp[3].txt" or die $!; ... foreach (@colvalues1){print $out1 "$_"}; foreach (@colvalues2){print $out2 "$_"}; foreach (@colvalues3){print $out3 "$_"};

Replies are listed 'Best First'.
Re: push values to an element of an array and read the same
by Athanasius (Archbishop) on Sep 28, 2017 at 07:32 UTC
    push @colvalues1, $allcols[0],':',$allcols[1],"\n";

    This pushes 4 separate values onto the array. If @colvalues1 was empty before the operation, the push populates it like this:

    17:27 >perl -MData::Dump -wE "my @allcols = ('abc', 'def'); my @colval +ues1; push @colvalues1, $allcols[0],':',$allcols[1],qq[\n]; dd \@colv +alues1;" ["abc", ":", "def", "\n"] 17:27 >

    Perhaps you intended to concatenate these 4 fields into a single string?

    17:28 >perl -MData::Dump -wE "my @allcols = ('abc', 'def'); my @colval +ues1; push @colvalues1, $allcols[0].':'.$allcols[1].qq[\n]; dd \@colv +alues1;" ["abc:def\n"] 17:29 >

    That is, replace the commas (which produce a list) with dots (which concatenate).

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: push values to an element of an array and read the same
by GrandFather (Saint) on Sep 28, 2017 at 08:53 UTC

    Is this homework relating to restructuring code, or is it real life application code you want to clean up? If it's real life code it'd help a lot if you give us the bigger picture so we can give you better advice. If it's homework tell us and tell us where you are having trouble.

    In either case showing us some real code and the wanted output will help us understand the problem.

    Premature optimization is the root of all job security
Re: push values to an element of an array and read the same
by Corion (Patriarch) on Sep 28, 2017 at 07:19 UTC

    What does not work?

    You can help us help you better by providing code that we can run and also providing a small sample of representative input data and the output you get.