Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

split efficiency needed

by Anonymous Monk
on Jan 21, 2004 at 13:47 UTC ( [id://322879]=perlquestion: print w/replies, xml ) Need Help??

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

I want to parse this line and just print the date and Time.

Out of this:
-rwxr-xr-x 1 svcn-3 ymn-3 7618486 Jan 20 21:42 20040120-299-x49.exe
I want this:
Updated on Jan 20 at 21:42 hours
I would put this in a variable:
my $var = '-rwxr-xr-x 1 svcn-3 ymn-3 7618486 Jan 20 21:42 20040120- +299-x49.exe'; my @newvar = split ' ', $var; print "Update at $newvar[5] $newvar[6] at $newvar[7]";
Any better way to do this??

Replies are listed 'Best First'.
Re: split efficiency needed
by markov (Scribe) on Jan 21, 2004 at 14:21 UTC

    I do not know you exact environment, but apparently you are processing ls output on a Unix/Linux system. If so, would it be possible to avoid using ls in the first place... The reason for this, is that the date format in the ls output depends on the locale settings and may therefore change. In my settings, it is 2004-01-21!

    Maybe you can rewrite the code to this:

    my $mtime = (stat $file)[9]; use POSIX 'strftime'; print strftime "any format you like", localtime $mtime;
Re: split efficiency needed
by Roger (Parson) on Jan 21, 2004 at 13:51 UTC
    Split is quite efficient on short and simple strings. The following is what I normally do, with a one-liner, not necessarily better, but less typing.
    my $var = '-rwxr-xr-x 1 svcn-3 ymn-3 7618486 Jan 20 21:42 20040120- +299-x49.exe'; printf "Update at %s %s at %s hours\n", (split /\s+/, $var)[5,6,7];

    Here's another method I can think of that might improve the efficiency a bit if the string is long and has plenty of spaces. This approach only remembers the required fields and throws away the rest.
    printf "Update at %s %s at %s hours\n", ($var =~ /^(?:\S+\s+){5}(\S+)\s+(\S+)\s+(\S+)/);

      thanks

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (6)
As of 2024-04-25 13:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found