CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Perl Substr Isolating one field of a string

 



popeye
Novice

Jan 7, 2014, 4:34 AM

Post #1 of 4 (1013 views)
Perl Substr Isolating one field of a string Can't Post

 
What is the Perl substr equivalent to the following Ksh code.




Code
echo "System_Uptime : 109 days, 23:32" | sed 's/.* \: //g' | awk '{print $1}'


Output is :


Quote
109


EDITED :

Sorry I should have given some examples of what I tried.
This kind of works, but the field Im after could be in the form of "14:32". What I really after is what ever is betwen :, space and space days.


Code
$string = "System_Uptime : 109 days, 23:32"; 
$x = substr($string, 16,3);
print "$x\n";


Thanks


(This post was edited by popeye on Jan 7, 2014, 4:41 AM)


BillKSmith
Veteran

Jan 7, 2014, 5:30 AM

Post #2 of 4 (1009 views)
Re: [popeye] Perl Substr Isolating one field of a string [In reply to] Can't Post

You can almost duplicate your shell script in perl.

Code
use strict; 
use warnings;
my $string = "System_Uptime : 14:32 days, 23:32 ";
$string =~ s/.* \: //g;
my $x = (split /\s/, $string)[0];
print "$x\n";


I prefer:

Code
use strict; 
use warnings;
my $string = "System_Uptime : 14:32 days, 23:32 ";
my ($x) = $string =~ /: (.*) days/;
print "$x\n";

Good Luck,
Bill


2teez
Novice

Jan 7, 2014, 2:02 PM

Post #3 of 4 (1002 views)
Re: [popeye] Perl Substr Isolating one field of a string [In reply to] Can't Post

Hi,
You can use both index and substr to get what you wanted. Like this:

Code
use strict; 
use warnings;

while ( my $string = <DATA> ) {
chomp $string;
my $start = index $string, ':';
my $end = index $string, ' days';
print substr( $string, $start + 1, $end - $start ), $/;
}

__DATA__
System_Uptime : 109 days, 23:32
System_Uptime : 14:32 days, 23:32



popeye
Novice

Jan 8, 2014, 4:15 AM

Post #4 of 4 (977 views)
Re: [2teez] Perl Substr Isolating one field of a string [In reply to] Can't Post

 
Thanks to all. Sometimes, once I see the solution, I ask myself "Why didnt I see that !!"

Thanks agan !

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives