in reply to Truncate Data from MySQL

Wrapped up in a subroutine:
use strict; my $string = 'one two three four five six seven eight nine ten eleven twelve +thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty' +; { local $, = ', '; print first_x( $string, 10 ), "\n"; } print scalar first_x( $string, 10 ), "\n"; sub first_x { return wantarray ? ( split /\s+/, $_[0], $_[1] + 1 )[ 0 .. $_[1] - 1 ] : join ' ', ( split /\s+/, $_[0], $_[1] + 1 )[ 0 .. $_[1] - 1 +]; }
Output:
one, two, three, four, five, six, seven, eight, nine, ten, one two three four five six seven eight nine ten
If called in list context, it returns a list with the "x" first words. If called in scalar context it returns a string of the first "x" words joined by spaces.

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^2: Truncate Data from MySQL
by wol (Hermit) on Jul 07, 2009 at 22:27 UTC
    Going off on a bit of a tangent, it just occurred to me that it should be possible to write the first_x function recursively, to reduce code duplication. Ie:
    sub first_x { return wantarray ? ( split /\s+/, $_[0], $_[1] + 1 )[ 0 .. $_[1] - 1 ] : join ' ', first_x( @_ ); }
    Maybe a similar pattern could be applied in other circumstances as well.

    --
    use JAPH;
    print JAPH::asString();

      I'm not particularly fond of the extra trip through the sub when we could use a lexical to store the data:
      sub first_x { my @data = ( split /\s+/, $_[0], $_[1] + 1 )[ 0 .. $_[1] - 1 ]; return wantarray ? @data : join ' ' , @data ; }
      then again, I don't like the 0..n slice. Why not just use pop?
      sub first_x { my @data = split /\s+/, $_[0], $_[1] + 1 ; pop(@data); #throw away last element return wantarray ? @data : join ' ' , @data ; }
      peace, spazm