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

Can anyone please explain to me why these two arrays are different?? ( $array[1] has been read from a file which has then been split into elements of an array, it now contains this:  apples    pears    oranges in tab-delimited text.
my @fruit = $array[1]; my @fruit = ('apples', 'pears', 'oranges');
the program i am writing works with the latter, not the former. If they are different, how can I convert the former into the latter as it it the former that i need to work with??? cheers.................

update (broquaint): escaped brackets with <code> tags to avoid linking

Replies are listed 'Best First'.
Re: odd behaving arrays
by LTjake (Prior) on Nov 29, 2002 at 13:25 UTC
    If i understand you correctly, then $array[1] looks like this "apples\tpears\toranges"? If, so, you'll have to use split to create the array you want. example:
    $array[1] = "apples\tpears\toranges"; my @fruit = split(/\t/, $array[1]); print "[$_]\n" foreach @fruit;
    Results:
    [apples] [pears] [oranges]


    --
    Rock is dead. Long live paper and scissors!
Re: odd behaving arrays
by Abigail-II (Bishop) on Nov 29, 2002 at 13:26 UTC
    The first line will create an array with one element; its sole element containing whatever $array [1] contains. The second line creates an array with 3 elements.

    I don't know how to convert the former. I don't what you expect $array [1] to contain. I have a pretty good guess what it does contain, but then, the question wouldn't make much sense.

    Abigail

Re: odd behaving arrays
by marinersk (Priest) on Nov 29, 2002 at 15:54 UTC
     > my @fruit = $array[1];

    According to your description, $array[1] has apples pears oranges in it (with tabs instead of spaces). Therefore, this line of code takes apples pears oranges and sticks it in $fruit[0]. Remember that Perl arrays start at [0]. Essentially, then, you've taken the second element of @array and stuck it into the first (and only) element of @fruit.

     > my @fruit = ('apples', 'pears', 'oranges');

    This takes apples and sticks it in $fruit[0], takes pears and sticks it in $fruit[1], and oranges and sticks it in $fruit[2]. This results in an array @fruit with three elements.

    Does that help?

    - Steve