Hi Punit,

some comments on your code:

On Thu, 3 Jan 2013 15:53:20 +0530
punit jain <contactpunitj...@gmail.com> wrote:

> Hi,
> 
> I am facing issues in parsing using Regex. The problem definition is as
> below : -
> 
> A file with data :-
> 
> BEGIN
> country Japan
> passcode 1123
> listname sales
> contact ch...@example.com
> contact m...@example.com
> END
> 
> BEGIN
> country Namibia
> passcode 9801
> listname dept
> contact l...@example.com
> END
> 
> BEGINDL
> country US
> passcode 4123
> listname Investment
> member a...@example.com
> member b...@example.com
> ENDDL
> 
> BEGIN
> country US
> passcode 4432
> listname testing
> contact lore...@test.com
> contact a...@test.com
> END
> ......
> .....
> ...
> ..
> .
> 
> I want to parse it in such a way that  all data with BEGIN and END goes in
> one file and BEGINDL and ENDDL goes in other with kind of processing I want
> to so.
> 
> I am using below code but doesnot work : -
> 
> #!/usr/bin/perl

use strict; use warnings;

> my $file=shift;

Don't call variables "file". In your case it should be "filename".

> open( FH , "$file" ) or die("open failed: $!\n");

Don't use bareword file handles or two args open.

> open ($fh1, ">/tmp/a");
> open ($fh2, ">/tmp/b");

use autodie and three args open.

> my $check=0;
> while (<FH>) {

chomp and use a lexical variable to iterate over the lines (say $line or $l)
instead of $_ which can be clobbered and devastated very easily.

> #    next unless /BEGIN/ .. /END/ || /BEGINDL/ .. /ENDDL/ || eof;
>     if($_ =~ /BEGIN$/ || ($check == 0) ) {

You probably want « $_ eq 'BEGIN' » instead (after chomp).

>         print $fh1 $_;
>         $check = 0;
>         if($_ =~ /END$/) {
>         $check = 2;
>         }
>     }elsif($_ =~ /BEGINDL/ || ($check == 1)) {
>         print $fh2 $_;
>         $check = 1;
>         if($_ =~ /ENDDL/) {
>         $check = 2;
>         }
>     }
>     next unless($check == 2);

Always label your nexts (and in this case I think it is redundant).

See:

http://perl-begin.org/tutorials/bad-elements/

Regards,
        
        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Stop Using MSIE - http://www.shlomifish.org/no-ie/

Bigamy: Having one wife too many.
Monogamy: The same thing!           — Unknown source.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to