Loading ...
Sorry, an error occurred while loading the content.

Re: [PBML] splitting a $variable

Expand Messages
  • Andrew Johnson
    Nathan wrote: ! I am trying to split a $variable into its component ! characters. ! ! So $char = text; would be split into t,e,x and t ! ! I tried: ! !
    Message 1 of 3 , Aug 31, 2000
    • 0 Attachment
      Nathan wrote:
      ! I am trying to split a $variable into its component
      ! characters.
      !
      ! So $char = text; would be split into t,e,x and t
      !
      ! I tried:
      !
      ! $messagelength=length($message);
      ! for ($counter=0; $counter<$messagelength; $counter++)
      ! {
      ! $messagechar[$counter]=substr($message,$counter,$counter+1);
      ! }
      !
      ! But this doesnt seem to work. Does anyone have any
      ! ideas why ?

      Yes -- look at what the arguments to your substr() call will be each
      time through your loop (in particular, look at your third argument).

      first time, $counter is 0 so the line is saying:

      $messagechar[0] = substr($message, 0, 0 + 1)

      The second time, $counter is 1 so:

      $messagechar[1] = substr($message, 1, 1 + 1)

      now you are asking for a substring of length 2. What you wanted was
      to make the third argument just a single 1:

      $messagechar[$counter]=substr($message,$counter,1);

      But note that you can use the split() function with a null regex to
      split apart strings at every character:

      my $string = 'foobar blah quux';
      my @chars = split //, $string;
      print join(':', @chars), "\n";

      This prints:

      f:o:o:b:a:r: :b:l:a:h: :q:u:u:x

      regards,
      andrew

      --
      Andrew L. Johnson http://members.home.net/perl-epwp/
      Doing linear scans over an associative array is like
      trying to club someone to death with a loaded Uzi.
      -- Larry Wall
    Your message has been successfully submitted and would be delivered to recipients shortly.