Why do you think the anon sub should be faster? It does the same thing as your simple sprintf -- but it has the overhead of creating a closure too. The anon sub should be slower.
Generally you shouldn't use anon subs unless you can factor out some (expensive) common code, or you want to pass functions as arguments to modify how other subs behave. Closures are fairly large objects and can be difficult for people to understand.
Here's an example of using a closure to factor out the relatively static year-month-day-hour formatting.
sub setup_file_name_generator { # Generate file names of the form # "year-month-day-hour-pid-count". # # The year-month-day-hour-pid portion # is cached and will expire on the hour. my $time = time; my @time = localtime($time); my $base = sprintf('%4d-%02d-%02d-%02d-%d-', $time[5]+1900, $time[4]+1, $time[3], $time[2], $$); my $count = 0; my $expires = $time + 60 * (60 - $time[1]); *generate_file_name = sub { $time = time; if ($time >= $expires) { setup_file_name_generator(); return generate_file_name(); } else { my $name; do { ++$count; $name = $base . $count; } while (-e $name); return $name; } } } setup_file_name_generator(); my $name = generate_file_name();
I've tested the code a bit, but it definitely needs more testing to ensure that the cache expires properly on the hour. It's rather defensive code though -- the -e $name check will prevent collisions even if the cache doesn't work perfectly.
In reply to Re: Re: Timestamp as a Filename Collection
by blssu
in thread Timestamp as a Filename Collection
by hiseldl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |