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

split a string at a defined index

by avanta (Beadle)
on Mar 29, 2010 at 05:17 UTC ( [id://831557]=perlquestion: print w/replies, xml ) Need Help??

avanta has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,
I know this sounds a stupid question but I am not able to get a technical answer for this.

Suppose I wish to split a list of strings, eg.
www,google,yahoo,345 www,google,yahoo,75323
such that i wish to have the split output of each row as
$var1=www,google,yahoo $var2=345 and so on...
A simple split will split the string as
$str="www,google,yahoo,345"; my ($var1,$var2)=split(/,/,$str); Output: $var1=www $var2=google
So if I wish to get the desired output I need to split at the last comma(,). How can I do it? Pleas help....

AvantA

Replies are listed 'Best First'.
Re: split a string at a defined index
by BrowserUk (Patriarch) on Mar 29, 2010 at 06:18 UTC

    You can split at the last comma by using a lookahead to check there are no more commas:

    print for split /,(?=[^,]+$)/, "www,google,yahoo,345";; www,google,yahoo 345

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      ... and  split on a specific index (without using substr):

      >perl -wMstrict -le "my $s = 'www,google,yahoo,345'; my ($v1, $v2) = split m{ (?<= \A .{16}) , }xms, $s; print qq{[$v1] [$v2]}; " [www,google,yahoo] [345]

        I suspect that by "at a defined index", the IP meant "the third comma" rather than "the 16th character position".

        If he does mean the 16th position, using substr is far clearer and vastly more efficient.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
Re: split a string at a defined index
by wfsp (Abbot) on Mar 29, 2010 at 07:15 UTC
    You don't always have to use a regex (in split or otherwise). :-)
    #! /usr/bin/perl use strict; use warnings; my $line = q{www,google,yahoo,345}; my $comma = rindex($line, q{,}); print substr($line, 0, $comma), qq{\n}; print substr($line, $comma+1);
Re: split a string at a defined index
by almut (Canon) on Mar 29, 2010 at 07:16 UTC

    Another one  (using rindex):

    sub mysplit { my $s = shift; my $p = rindex $s, ','; return ( substr($s,0,$p), substr($s,$p+1) ); } my ($var1, $var2) = mysplit('www,google,yahoo,345');
Re: split a string at a defined index
by CountZero (Bishop) on Mar 29, 2010 at 06:40 UTC
    And one more solution:
    use strict; use warnings; while (my $row = <DATA>) { chomp $row; my @elements = split ',', $row; my $tail = pop @elements; my $body = join ',', @elements; print "$body -- $tail\n"; } __DATA__ www,google,yahoo,345 www,google,yahoo,75323

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: split a string at a defined index
by Anonymous Monk on Mar 29, 2010 at 05:50 UTC
    There are more concise solutions, but few as mappily delicious as this one:
    my ($var1, $var2) = reverse # reverse order of split strings map {scalar reverse} # reverse characters back map { split(/,/, $_, 2) } # split off first field map {scalar reverse} # reverse characters qq(www,google,yahoo,345) # string ;
    # perl -le'print for reverse map {scalar reverse} map { split(/,/, $_, + 2) } map {scalar reverse} qq(www,google,yahoo,345);' www,google,yahoo 345
Re: split a string at a defined index
by Punitha (Priest) on Mar 29, 2010 at 05:32 UTC

    Hi AvantA,

    Try this

    $str="www,google,yahoo,345"; my ($var1,$var2)= $str =~/^([^\n]+),([^\n]+)$/;

    Punitha

Re: split a string at a defined index
by JavaFan (Canon) on Mar 29, 2010 at 14:11 UTC
    $var1 = "www,google,yahoo,345"; $var1 =~ s/,([^,]*)\z//; $var2 = $1;

Log In?
Username:
Password:

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

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

    No recent polls found