Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

How to get an integer sub string between two string

by ppp (Acolyte)
on Jan 17, 2015 at 08:01 UTC ( [id://1113578]=perlquestion: print w/replies, xml ) Need Help??

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

I have a string like this :
Address: 100.64.52.98 Time Fri Jan 16 21:44:35 2015 End

How to extract "21:44:35" from it ?

my try is
my ($a1, $a2, $a3, $a4, $a5, $a6, $a7, $a8,$a9, $a10,$a11) = split +//, $line;

Replies are listed 'Best First'.
Re: How to get an integer substring between two strings
by Athanasius (Archbishop) on Jan 17, 2015 at 08:14 UTC

    Hello ppp,

    Splitting on the empty pattern, //, gives you every character separately. You want to split on whitespace, for example /\s+/. Update: Or use " " (a single space literal string) instead of a regular expression. See split, the paragraph beginning “As another special case, split emulates the default behavior of the command line tool awk...”

    Note: if you know that the field you want is always the seventh in the line, you can get it directly, without declaring all those unused variables:

    18:09 >perl -wE "my $line = 'Address: 100.64.52.97 Time Fri Jan 16 21: +44:35 2015 End'; say +(split /\s+/, $line)[6];" 21:44:35 18:11 >

    Hope that helps,

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

Re: How to get an integer sub string between two string
by Corion (Patriarch) on Jan 17, 2015 at 08:05 UTC

    What do you see as problematic with your current approach?

    Maybe you want to use a regular expression instead?

    $line =~ /\b(\d\d:\d\d:\d\d)\b/ or die "No time in '$line'"; my $time= $1;
Re: How to get an integer sub string between two string
by Anonymous Monk on Jan 17, 2015 at 08:09 UTC
    # Address: 100.64.52.98 Time Fri Jan 16 21:44:35 2015 End # ........ ............ .... ... ... .. ..:..:.. .... ... # Address: ............ Time ... ... .. ..:..:.. .... ... my( $stuff, $fri, $jan, $day, $hour, $min, $sec, $y +ear, $end ) = m{Address: (............) Time (...) (...) (..) (..):(..):(..) (....) +(...)}ms;
      This will not work when the IP address (or any other field) might have a different length...
      Compare 1.2.3.4 with 111.222.111.222 for example.
        If data isn't fixed length use \S+, perlrequick, its for ppp :)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (2)
As of 2024-04-26 01:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found