in reply to using split on every element in an array

You're calling split() in a void context, so whatever returned values it may be generating are just being discarded. You'd want to do something like push @split_data, split( /\t/ ) to save them off.

Or even better, look at Text::CSV_XS and see if that'll handle your data parsing needs.

Replies are listed 'Best First'.
Re: Re: using split on every element in an array
by Anonymous Monk on Jan 17, 2003 at 15:21 UTC
    Is it possible to automatically convert every element of an array into a newly named scalar variable (each of which has a different name)??

      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.

      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}

      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

Re: Re: using split on every element in an array
by Arien (Pilgrim) on Jan 18, 2003 at 05:46 UTC
    You're calling split() in a void context, so whatever returned values it may be generating are just being discarded.

    Actually, no: the values are saved in @_. However, this usage of split is deprecated and will generate a warning when you use warnings or -w.

    — Arien

      You are correct. I thought it was only scalar context in which that happened, but it also apparently does it in void context as well. Good catch.