On Mon, Dec 8, 2008 at 13:54, sanju.shah <[EMAIL PROTECTED]> wrote:
> I am looking for some suggestions on any advanced functions Perl might
> have that i might be missing.
>
> Basically, I have an array with column widths. Next I have a string. I
> would like to extract the number of characters based on the column-
> widths in the array. I have already tried using substr but is there
> any other way of extracting?
>
> eg:
>
> @col_width = (4,2,17);
> my $str = 'Perl is amazing language';
>
> I'd like a one-line command (if possible) to store 'Perl' in $a, 'is'
> in $b & 'amazing language' in $c.
snip

First, never use $a or $b.  Those are special variables* in Perl.

It looks like you want split**:

my ($x, $y, $z) = split / /, $str, 3;

but since you never told us why "Perl" should wind up in the first
variable, "is" in the second, etc. that could be wrong.  You may want
a regex***, or it is even possible you could want the number of words
in each string should correspond to the Fibonacci sequence:

#!/usr/bin/perl

use strict;
use warnings;

my $str = join " ", "a" .. "t";

my @words = split / /, $str;
my $p     = 0;
my $n     = 1;
my @seq;
while (@words) {
        push @seq, join " ", splice @words, 0, $n;
        ($n, $p) = ($n + $p, $n);
}

print map { "$_\n" } @seq;

* http://perldoc.perl.org/perlvar.html#$a
** http://perldoc.perl.org/functions/split.html
*** http://perldoc.perl.org/perlretut.html

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to