Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Break sentence into two part

by rnewsham (Curate)
on Jan 24, 2015 at 07:30 UTC ( #1114341=note: print w/replies, xml ) Need Help??


in reply to Break sentence into two part

Something like below may do what you want. Although it's not exactly clear from your question why you want to do this, or what you have tried so far. You may get a better answer, if you can provide more details of what problem you are trying to solve and example code you have tried.

use strict; use warnings; my $sentence = 'Perl 5 is a highly capable, feature-rich programming l +anguage with over 27 years of development.'; my @words = split( ' ', $sentence); my $midpoint = sprintf("%d", scalar @words / 2); my ( @first_half, @second_half ); my $count = 0; for ( @words ) { push @first_half, $_ if $count <= $midpoint; push @second_half, $_ if $count > $midpoint; $count++; } print join( ' ', @first_half ) . "\n"; print join( ' ', @second_half ) . "\n";
<code> Output: Perl 5 is a highly capable, feature-rich programming language with over 27 years of development

Replies are listed 'Best First'.
Re^2: Break sentence into two parts
by Athanasius (Bishop) on Jan 24, 2015 at 07:43 UTC

    Yes, that’s how I would approach the problem. But there’s no need to populate new arrays using push, etc.: just use array slices directly:

    my $first_half = join(' ', @words[0 .. $midpoint]); my $second_half = join(' ', @words[$midpoint + 1 .. $#words ]);

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re^2: Break sentence into two part
by pme (Prior) on Jan 24, 2015 at 09:08 UTC
    The midpoint calculation also can be written as:
    my $midpoint = int(@words / 2);

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2020-12-01 15:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How often do you use taint mode?





    Results (11 votes). Check out past polls.

    Notices?