Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: substr question

by linuxer (Deacon)
on Jun 18, 2010 at 16:50 UTC ( #845408=note: print w/ replies, xml ) Need Help??


in reply to substr question

I modified your problem definition into:

How to split a string into several substrings (of a given maximum length) without breaking a word when splitting.

I found this (quickly hacked) solution:

#! /opt/perl/bin/perl use strict; use warnings; my $text = "Hello, I am a perl/mysql programmer, but am self taught so + I do not know all the awesome features Perl has, however, I am ok at + it though, I guess."; sub split_at { my ( $text, $len ) = @_; my @result; my @parts = split /[ ]/, $text; my $short = shift @parts; while ( @parts ) { if ( length($short) + length($parts[0]) < $len ) { $short = join( ' ', $short, shift @parts ); } else { push @result, $short; $short = shift @parts; } } push @result, $short; return @result; } { local $, = local $\ = $/; print split_at( $text, 100 ); # beware print split_at( 'a'x110, 100 ); }

Limitation: If the given string doesn't contain any whitespace (\x20), it won't split at all.

If you just want/need the first substring, just use the first returned element.

Updates:

  • cleaned up code
  • fixed comparison; thanks, rowdog


Comment on Re: substr question
Select or Download Code
Re^2: substr question
by rowdog (Curate) on Jun 18, 2010 at 21:20 UTC
    if ( length($short) + length($parts[0]) <= $len ) { $short = join( ' ', $short, shift @parts ); }

    The length is off by one because you add not only the part, but a new space as well. The easy fix is to delete the = from <= $len

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://845408]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2014-12-19 03:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (70 votes), past polls