Hien Le wrote: > Hello, Hello,
> Given the string 'abcdefghijklmnopq', I wish to add a line break every > 5 characters: > > abcde > fghij > klmno > pq $ perl -e' my $foo = q[abcdefghijklmnopq]; print "$foo\n"; $foo =~ s/(.{0,5})/$1\n/g; print $foo; ' abcdefghijklmnopq abcde fghij klmno pq > Method 1 below works, but my split() in method 2 captures 'something > unexpected' at each match. Could someone please tell me what is split > capturing that I am not seeing? split( /X/, 'aXb' ) splits the string using the pattern and returns the list ( 'a', 'b' ). split( /(X)/, 'aXb' ) splits the string using the pattern and returns the list ( 'a', 'X', 'b' ). Everything not in the pattern is returned in the list unless you use capturing parentheses and then everything in the capturing parentheses is returned as well. > My script: > ========== > > #!/usr/bin/perl -w > > use strict; > > my $foo = 'abcdefghijklmnopq'; > > # Method 1 > print( "\nMethod 1\n" ); > my $foo_length = length( $foo ); > for( my $i = 0; $i < $foo_length; $i += 5 ) > { > my $bar1 = substr( $foo, $i, 5 ); > print( $bar1, "\n" ); > } > > # Method 2 > print( "\nMethod 2\n" ); > my @bar2 = split( /([a-z]{5})/, $foo ); # Captures white-spaces ?!? > my $bar2_nb = @bar2; > print( join( "\n", @bar2) ); > print( "\nElements in array = ", $bar2_nb, "\n" ); # 7 elements in the > array. > > __END__ $ perl -e' my $foo = q[abcdefghijklmnopq]; print "$foo\n"; my @bar = unpack q[(a5)*], $foo; print map "$_\n", @bar; ' abcdefghijklmnopq abcde fghij klmno pq $ perl -e' my $foo = q[abcdefghijklmnopq]; print "$foo\n"; my @bar = $foo =~ /.{0,5}/g; print map "$_\n", @bar; ' abcdefghijklmnopq abcde fghij klmno pq John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>