Re: Help with String/Array manipulation



On Mon, Dec 8, 2008 at 13:54, sanju.shah <sanju.shah@xxxxxxxxx> 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.
.



Relevant Pages

  • Newbie: Array of pointers to strings questions.
    ... What I'm trying to do is extract information from one file and insert ... and the information in each case is extracted as a string. ... the relevant file is read into a temp file, ... but handling the array was a problem. ...
    (comp.lang.c)
  • Re: Help with String/Array manipulation
    ... I have an array with column widths. ... Next I have a string. ... I have already tried using substr but is there ...
    (perl.beginners)
  • Re: Function returns Datatype Mismatch
    ... >> Public Function Extract(Account_Code As String) As String ... Tokens is an array of strings, ... > Extract = Tokens ... > Tokensyields "A" ...
    (microsoft.public.access.modulesdaovba)
  • Re: Function returns Datatype Mismatch
    ... > Public Function Extract(Account_Code As String) As String ... Tokens is an array of strings, ... Extract = Tokens ... Tokensyields "A" ...
    (microsoft.public.access.modulesdaovba)
  • Re: Array problem (MySQL/PHP)
    ... You pass a string to 'TableData'. ... the same value (as returned from the same array '$row_Recordset1', ... same key '$slot') is appended to the end of that returned string. ... In the 'if' block you seem to be looking to extract a string from ...
    (alt.php)