Dear Masters,
My code below decompose a string into tuples (pair).
It already does the job, but to me it seems very slow and clumsy.
Is there a faster and more compact way to do it?
See the result below for answers:
use Data::Dumper;
my $s1 = 'X -4 Y 3 Z';
my $s2 = 'W 1 X -4 Y 3 Z';
my $s3 = 'X 2 Y';
my $s4 = 'A -4 B -4 C -4 A -4 B';
decomp_str($s1);
decomp_str($s2);
decomp_str($s3);
decomp_str($s4);
sub decomp_str
{
my $s1 = shift;
my @ar = split (" ",$s1);
my @dcomp;
push @dcomp, "$ar[0] $ar[1] $ar[2]";
foreach my $i ( 2 .. $#ar-1 )
{
if ($ar[$i] =~ /[A-Z]+/)
{
push @dcomp, "$ar[$i] $ar[$i+1] $ar[$i+2]";
}
}
print Dumper \@dcomp;
return \@dcomp;
}
The answers are:
$VAR1 = ['X -4 Y','Y 3 Z']; # For $s1
$VAR1 = ['W 1 X','X -4 Y','Y 3 Z']; # For $s2
$VAR1 = ['X 2 Y']; # For $s3
$VAR1 = ['A -4 B','B -4 C','C -4 A','A -4 B']; # For $s4
---
neversaint and everlastingly indebted.......
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.