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

How to handle a variable number of results from split()?

by Anonymous Monk
on Jul 20, 2005 at 16:14 UTC ( #476553=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I have a file(s) with asimilar lines:
I want to split by /-/ but process each split separatly.
foreach (<>) { ($num1, $num2) = split(/-/; }
So firstly $num1=1 and $num2=2 and do something with these. Then split the second set $num1=3 and $num2=4 and process these. The only problem here is that the number of splits is not consistent so i can not declare each variable. Is this possible?

Edited by Arunbear: Changed title from 'split', as per Monastery guidelines

Replies are listed 'Best First'.
Re: How to handle a variable number of results from split()?
by AReed (Pilgrim) on Jul 20, 2005 at 16:28 UTC
    I'm sure that there's a more compact way to do this, but I think that this does what you are looking for.

    I'm also assuming that you meant that each line of your input file had a different number of "dash pairs" such as:

    --- beginning of data --- 1-2,3-4,2-5 2-1,2-5 3-5,1-9,2-2,4-8 --- end of data --- use warnings; use strict; while (<>) { chomp; my @dashpairs = split(/,/); foreach my $dashpair (@dashpairs) { my ($num1, $num2) = split(/-/,$dashpair); print "$num1 - $num2\n"; } }
      Aye, there is.. and I'm sure there's a more compact way than this one as well :)
      #!/usr/bin/perl use strict; use warnings; { local ($,,$\) = (" - ","\n"); while (<DATA>) { chomp; print split(/-/) for split(/,/) } } __DATA__ 1-2,3-4,2-5 2-1,2-5 3-5,1-9,2-2,4-8
        Well, if that's exactly how you want the output:
        { local $/; local $_ = <DATA>; s/,/\n/g; s/-/ - /g; print }
        open P, ' | perl -laF, -ne "s/-/ - /, print for @F" '; print P <DATA>; close P;
        (Some things are done more succinctly on the command line.)
      thanks for ur help, this certainly does help

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://476553]
Approved by sschneid
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2017-07-24 07:08 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (348 votes). Check out past polls.