http://www.perlmonks.org?node_id=993367

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

Please help me in this... Say my code is as follows:...
VAR DS 0D DC AL1(045),AL2(286),AL2(117),AL2(290)
I need to split this and push to my output file in the below 2 formats...

format1:

VAR DS 0D DC AL1(045) DC AL2(286) DC AL2(117) DC AL2(290)

format2:

VAR D F1 A 045 F2 A 286 F3 A 117 F4 A 290

I want to perform this action using Perl.

Replies are listed 'Best First'.
Re: How to split
by Anonymous Monk on Sep 13, 2012 at 05:44 UTC

    Please help me in this... Say my code is as follows:...

    FWIW, when we talk about "code" we usually mean "source code" as in "perl program", not about the data

    Here is a start, run with it

    #!/usr/bin/perl -- use strict; use warnings; my $blah = ' VAR DS 0D DC AL1(045),AL2(286),AL2(117),AL2(290)'; my ( $top, $bottom ) = split /[\r\n]+/, $blah; print "$top\n"; my( $prefix, @biscuits ) = grep length, split /[\s,]+/, $bottom; for my $tack ( @biscuits ){ print "$prefix $tack\n"; } __END__ VAR DS 0D DC AL1(045) DC AL2(286) DC AL2(117) DC AL2(290)

      Adventures in regular expressions

      #!/usr/bin/perl -- use strict; use warnings; use Data::Dump; my $blah = ' VAR DS 0D DC AL1(045),AL2(286),AL2(117),AL2(290)'; my ( $top, $bottom ) = split /[\r\n]+/, $blah; print "$top\n"; #~ my( $prefix, @biscuits ) = grep length, split /[\s,]+/, $bottom; my( $prefix, @biscuits ) = split /(?:(?<!^)\s+)|,/, $bottom; dd \$prefix, \@biscuits ; for my $tack ( @biscuits ){ print "$prefix $tack\n"; } __END__ $ perl shineon001 VAR DS 0D (\" ", ["DC", "AL1(045)", "AL2(286)", "AL2(117)", "AL2(290)"]) DC AL1(045) AL2(286) AL2(117) AL2(290)

        Adventures in regular expressions, part 2

        #!/usr/bin/perl -- use strict; use warnings; use Data::Dump; my $blah = ' VAR DS 0D DC AL1(045),AL2(286),AL2(117),AL2(290)'; my ( $top, $bottom ) = split /[\r\n]+/, $blah; print "$top\n"; #~ my( $prefix, @biscuits ) = grep length, split /[\s,]+/, $bottom; #~ my( $prefix, @biscuits ) = split /(?:(?<!^)\s+)|,/, $bottom; my( $prefix, @biscuits ) = split /(?:(?<!^)\b\s+)|,/, $bottom; dd \$prefix, \@biscuits ; for my $tack ( @biscuits ){ print "$prefix $tack\n"; } __END__ $ perl shineon002 VAR DS 0D ( \" DC", ["AL1(045)", "AL2(286)", "AL2(117)", "AL2(290)"], ) DC AL1(045) DC AL2(286) DC AL2(117) DC AL2(290)
Re: How to split
by cztmonk (Monk) on Sep 13, 2012 at 06:29 UTC

    What code did you try? See

    perldoc -f split split /PATTERN/,EXPR,LIMIT split /PATTERN/,EXPR split /PATTERN/ split Splits the string EXPR into a list of strings and returns that list. By default, empty leading fields are preserved, and empt +y trailing ones are deleted. (If all fields are empty, they are considered to be trailing.)
Re: How to split
by Anonymous Monk on Sep 13, 2012 at 08:37 UTC