Search code examples
arraysperlsplitvariable-length-array

Perl - Splitting a string


I'm doing an Array that contents each word of a phrase. When I try to split it and print the length then the console gives me an enormous number such as 111039391231319239188238139123919232913123... (more lines) why?

Here's my code:

$mynames = $texto3;
print $mynames. "\n";
@nameList = split(' ', $texto3);
#print @nameList.length();
for ($to = 0; $to<@nameList.length; $to++){
        if($to<@nameList.length) {
                @nameList[$to] = @nameList[$to] . "_" . @nameList[$to++];
         }
         print $to;
         #print @nameList[$to] . "\n";
 }
 $string_level2 = join(' ', @nameList);
 #print $string_level2;

Solution

  • To get the length of an array use scalar @nameList instead of @nameList.length.

    A typical for-loop uses the less-than operator when counting up, e.g.:

    for ( $to = 0; $to < scalar(@nameList); $to++ ) ...
    

    You should never use a post-increment unless you understand the side effects. I believe the following line:

    @nameList[$to] = @nameList[$to] . "_" . @nameList[$to++];
    

    ... should be written as ...

    
        $nameList[$to] = $nameList[$to] . "_" . $nameList[$to + 1];
    

    Finally the comparison you use should account for the boundary condition (because you refer to $to + 1 inside the loop):

    if( $to < (scalar(@nameList) - 1) ) {
      $nameList[ $to ] = $nameList[ $to ] . "_" . $nameList[ $to + 1 ];
    }