Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

split function

by Rajsai2825 (Novice)
on Dec 04, 2012 at 06:50 UTC ( #1007017=perlquestion: print w/ replies, xml ) Need Help??
Rajsai2825 has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, i want to raise a error if a split function dont find the pattern specifed. my ($s, $a, $c, $r) = (split /,/, $_) Input file: A|B|C|D here the pattern is comma but input file contains pipe. it should die here. could you please help me out handle this? If input file contains different delimiter other than one specified in split, it should die.

Comment on split function
Re: split function
by davido (Archbishop) on Dec 04, 2012 at 06:56 UTC

    Are you having trouble finding the answers to your previous question? Here's a link: Split function.

    If those answers prove unsuitable, follow-up in that thread seeking clarification.


    Dave

Re: split function
by AnomalousMonk (Monsignor) on Dec 04, 2012 at 08:11 UTC

    In addition to reviewing the post and accompanying replies linked by davido, please consider the following code. As noted in the previous discussion, split cannot be made to throw an exception if it finds nothing on which to split. Validation of input must be done separately. If you want the process to actually abort on any of the invalid conditions in the code below, replace warn wherever it appears with die (and also remove the associated  and next LINE expressions, although leaving them in will make no difference; they are simply redundant when used with die).

    >perl -wMstrict -le "my @lines = ( 'ABCD', 'A|B|C|D', 'A,B,C|D', 'A,B,C', 'A,B,C,D,E', 'A,B,C,D'); ;; LINE: for my $line (@lines) { print qq{processing '$line'}; ;; warn qq{'$line' has no comma} and next LINE if not $line =~ m{,}xms; warn qq{'$line' has nasty pipe} and next LINE if $line =~ m{ \| }xms; ;; warn qq{not exactly 4 fields in '$line'} and next LINE if 4 != (my ($s, $a, $c, $r) = split /,/, $line); ;; print qq{success: s '$s' a '$a' c '$c' r '$r'}; } " processing 'ABCD' 'ABCD' has no comma at -e line 1. processing 'A|B|C|D' 'A|B|C|D' has no comma at -e line 1. processing 'A,B,C|D' 'A,B,C|D' has nasty pipe at -e line 1. processing 'A,B,C' not exactly 4 fields in 'A,B,C' at -e line 1. processing 'A,B,C,D,E' not exactly 4 fields in 'A,B,C,D,E' at -e line 1. processing 'A,B,C,D' success: s 'A' a 'B' c 'C' r 'D'

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2014-09-02 23:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (34 votes), past polls