in reply to chopping a string into slices - is there a more elegant way to do it?

//g is a perfect generator.
$ml = 3; @a = "abcdefg" =~ /.{1,$ml}/g; say "@a"; __END__ abc def g
  • Comment on Re: chopping a string into slices - is there a more elegant way to do it?
  • Download Code

Replies are listed 'Best First'.
Re^2: chopping a string into slices - is there a more elegant way to do it?
by ikegami (Patriarch) on Nov 04, 2008 at 15:30 UTC
    /.{1,$ml}/sg if newlines are possible.
Re^2: chopping a string into slices - is there a more elegant way to do it?
by rovf (Priest) on Nov 04, 2008 at 13:12 UTC

    Thanks a lot to all of you for all the solutions provided. I think I will go for the //g version - I had completely forgotten that I can use the g modifier also with pattern matching, not only with pattern substitution. Really neat and compact solution!

    -- 
    Ronald Fischer <ynnor@mm.st>
Re^2: chopping a string into slices - is there a more elegant way to do it?
by LanX (Saint) on Nov 04, 2008 at 16:31 UTC
    talking about elegance

    IMHO additional parentheses improve the readability, emphasizing that the match-op is evaluated in a list-context. *

    @a = ( "abcdefg" =~ /.{1,$ml}/g ) ;
    or alternatively an extra newline
    @a = "abcdefg" =~ /.{1,$ml}/g ;
    well maybe a matter of taste ...

    * UPDATE: well it's not evaluated in list-context, but it empasizes the order of evaluation, making it IMHO more readable..

      IMHO additional parentheses improve the readability, emphasizing that the match-op is evaluated in a list-context.
      That's a really bad reason to use parenthesis, because they do NOT provide list context. Compare:
      $a = ("abcdefg" =~ /.{1,$ml}/g);
      Here parenthesis are used, but the match is in scalar context.
        UPDATE:(Dec 1. 2008) further down the thread I admit and show that I was wrong in this node! No need to discuss it further I don't think so, IMHO you are getting at first hand a list which is later reevaluated in scalar context!

        ... I'll run some tests to find the "truth" ; )

        UPDATE: I think your example is equivalent to

        my @a= ( $str =~ /.{1,$ml}/g ) ; $a=scalar @a; print $a;
        nevertheless is =~ evaluated in list-context!