Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Break sentence into two part

by roboticus (Chancellor)
on Jan 24, 2015 at 16:59 UTC ( [id://1114374]=note: print w/replies, xml ) Need Help??


in reply to Break sentence into two part

Mjpaddy:

You've already received some nice answers, so you won't want to use this ridiculous one. I just created it to amuse myself. I'm only posting it because: (a) It amused me to do so, and (b) 'cause I appropriated 2teez's signature line as part of the example, who might also be amused... ;^D

sub splitit { my ($left, @words, $right, $doit) = split /\s+/, shift; $right = pop @words; $doit = sub { my ($left, $right, @rest) = @_; if (@rest) { if (length($left) < length($right)) { return $doit->($left . ' ' . shift @rest, $right, @res +t); } else { return $doit->($left, pop(@rest) . ' ' . $right, @rest +); } } return $left, $right; }; $doit->( $left, $right, @words); } while (<DATA>) { s/\s+$//; print join(" | ", splitit($_)), "\n" unless /^$/;; } __DATA__ Now is the time for all good men to come to the aid of their party. The quick red fox jumped over the lazy brown dog. Time flies like an arrow, fruit flies like a banana. If you tell me, I'll forget. If you show me, I'll remember. If you involve me, I'm calling the cops.

Note: This code is an example of *bad* programming style, so don't use it, and it uses recursion instead of a simple loop which would be simpler and more efficient.

Update: A better version, which is still useless:

#!/usr/bin/env perl # # split a sentence into two roughly equal parts # use strict; use warnings; sub splitit { my $sentence = shift; my @words = split /(\s+)/, $sentence; my $doit; $doit = sub { my ($left, $right, @rest) = @_; if (@rest) { if (length($left) < length($right)) { return $doit->($left . shift @rest, $right, @rest); } else { return $doit->($left, pop(@rest) . $right, @rest); } } return $left, $right; }; return $doit->( '', '', @words); }

Finally, using a loop:

sub splitit { my @words = split /(\s+)/, shift; my ($left, $right) = ('', ''); while (@words) { if (length($left) < length($right)) { $left .= shift @words; } else { $right = pop(@words) . $right; } } return $left, $right; }

...roboticus

If ya wanna get to be good at anything, keep doing it. If ya wanna keep doing it, play with it and make it fun.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-04-20 00:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found