Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Perl split on regex match

by Athanasius (Archbishop)
on Jan 03, 2017 at 08:39 UTC ( [id://1178830]=note: print w/replies, xml ) Need Help??


in reply to Perl split on regex match

Hello Eshan_k,

Building on Corion’s answer:

use strict; use warnings; while (my $line = <DATA>) { chomp $line; my @cols = split /,/, $line; my @third = split /\./, $cols[2]; print join(',', @cols), "\n" if @third < 3; } __DATA__ cls1,37,Media.vdenc.abcunit,media_vd cls2,7,Media.Wigig.plsunit,media_vd cls3,27,Media.vdenc,media_vd cls4,47,Media.hevc,media_vd cls5,57,Media.ENC,media_vd

Output:

18:37 >perl 1736_SoPW.pl cls3,27,Media.vdenc,media_vd cls4,47,Media.hevc,media_vd cls5,57,Media.ENC,media_vd 18:37 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Perl split on regex match
by Random_Walk (Prior) on Jan 03, 2017 at 11:35 UTC

    Hi Athanasius

    Why do you print join ',', @cols when you already have $line in scope, with the complete line in it?

    I would be tempted to drop the chomp too, as we are never looking that far down the line. Then we have this code...

    use strict; use warnings; while (my $line = <DATA>) { my @cols = split /,/, $line; my @third = split /\./, $cols[2]; print $line if @third < 3; }

    Cheers,
    R.

    Pereant, qui ante nos nostra dixerunt!
      while (my $line = <DATA>) { print $line if (split /\./,$line) < 3; }
      But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)

        while (<DATA>) { print if (split /\./) < 3; }
        (but use a CSV parser!)


        The way forward always starts with a minimal test.

        That is assuming the '.' will not occur in any of the other fields.

        Cheers,
        R.

        Pereant, qui ante nos nostra dixerunt!
Re^2: Perl split on regex match
by LanX (Saint) on Jan 03, 2017 at 15:53 UTC
    Hi Athanasius

    Maybe nitpicking, but the OP said

    > > I want to print a line in which third field in the element is empty

    and not "less than 3 elements" (though he might have meant it)

    And it may be possible to split "a.b.c..e" where the 3rd element is empty.

    If this is a legal edge case I'd rather prefer unless length $cols[2]; over if @third < 3;

    (N.B. length undef and length "" are both false)

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2024-04-23 11:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found