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

I would like to parse minutes in the time string of the test code below with a one-liner instead of two:
#!/usr/bin/perl -w use strict; my $string="01:01:2000,14:01:12,1.584167"; my $time=(split(/\,/,$string))[1]; print "TIME: $time\n"; my $minute=(split(/:/,$string))[1]; print "MINUTE: $minute\n";
and.... no this is not homework.... I am simply searching for a better way to do it.
thanks.

Replies are listed 'Best First'.
Re: time string parsing question
by Roy Johnson (Monsignor) on Jun 02, 2005 at 19:38 UTC
    Assuming you really wanted the minutes from $time and not from $string,
    my ($time, $minute) = $string =~ /,(\d+:(\d+):\d+)/;

    Caution: Contents may have been coded under pressure.
Re: time string parsing question
by VSarkiss (Monsignor) on Jun 02, 2005 at 21:06 UTC
Re: time string parsing question
by tlm (Prior) on Jun 02, 2005 at 19:37 UTC

    Shorter is not always better... But you can always do

    my ( $minute, $time ) = ( $string =~ /^\d+:(\d+).*?,(\d+:\d+:\d+)/ )
    BTW, I think the above is consistent with what you posted, though it makes no sense to me that $minute does not come from the same substring as $time.

    the lowliest monk

Re: time string parsing question
by TedPride (Priest) on Jun 02, 2005 at 20:50 UTC
    Since the data / time is obviously fixed-length, there's no need for a two-step process or regex.
    my $string = '01:01:2000,14:01:12,1.584167'; my $min = substr($string, 14, 2); print $min;
    Or if you really MUST use split:
    my $string = '01:01:2000,14:01:12,1.584167'; my $min = (split /:/, (split /,/, $string)[1])[1]; print $min;
Re: time string parsing question
by GrandFather (Saint) on Jun 03, 2005 at 03:03 UTC
    This may be what you want if you are sure the time string format won't change too much:

    my ($time, $minute) = $string =~ /,(\d\d:(\d\d):\d\d)/g;


    Raise your eyes and look out of the rut.
Re: time string parsing question
by PerlBear (Hermit) on Jun 02, 2005 at 19:32 UTC
    Give this a try. It utilizes a combination of split and substr to dig out the minutes string piece that you are looking for.
    #!/usr/bin/perl -w use strict; my $string="01:01:2000,14:01:12,1.584167"; my $minute=substr(((split(/\,/,$string))[1]),3,2); print "MINUTE: $minute\n";
Re: time string parsing question
by sh1tn (Priest) on Jun 02, 2005 at 20:24 UTC
    my $minutes = (split /:/, (my $time = (split /\,/, $string)[1]))[1];


Re: time string parsing question
by graff (Chancellor) on Jun 03, 2005 at 02:17 UTC
    If the input string is always "MM:DD:YYYY,HH:MI:SS,FLOAT", the the minutes field ("MI") is always the fourth colon-delimited substring (regardless of the number of digits in each field). So this is all you need:
    my $string = "01:01:2000,14:01:12,1.584167"; my $minute = (split( /:/, $string ))[3];