in reply to Re: using split on every element in an array
in thread using split on every element in an array

Is it possible to automatically convert every element of an array into a newly named scalar variable (each of which has a different name)??
  • Comment on Re: Re: using split on every element in an array

Replies are listed 'Best First'.
Re: Re: Re: using split on every element in an array
by BrowserUk (Patriarch) on Jan 17, 2003 at 15:39 UTC

    Every element of an array is a named scalar variable.

    Eg. $array[3] = 'something';  $var = $array[4]; etc.

    You can therefore use them directly with split.

    Eg.

    for my $element (@array) { my @bits = split "\t", $element; #do something with the bits. }

    The contents of @array will remain unmodified for further use later unless you assign something to $element.

    It might be clearer to you written this way.

    for my $index (0 .. $#array) { # $#array is the numer of the highest e +lement. my @bits = split "\t", $array[$index]; }

    The first version is usually considered better though.


    Examine what is said, not who speaks.

    The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.

Re: Re: Re: using split on every element in an array
by thelenm (Vicar) on Jan 17, 2003 at 15:36 UTC
    It's possible, of course, but whenever you're thinking of creating a gazillion separate variables dynamically, you're usually better off using an array or hash. I'm not sure exactly what you want to do, but are you thinking of something like this?
    foreach my $item (@data) { push @data_split, [split /\t/, $item]; }
    Then you will have an array of arrayrefs that contain each line's data split on tabs. And @data is kept intact for you.

    -- Mike

    --
    just,my${.02}

Re3: using split on every element in an array
by Hofmator (Curate) on Jan 17, 2003 at 15:40 UTC
    I think you want something like the following inside your foreach loop. my ($name, $first_name, $tel, @rest) = split /\t/, $item; The array @rest is there as you are saying that you have a varying number of elements in each $item. Another alternative might be to just specify all possible elements and then check later if the variables are defined. Like this
    my ($name, $first_name, $tel, $address, $email, $last_field) = split / +\t/, $item; if (defined $last_field) { # do something }

    -- Hofmator