I had to think about that: the solution is to use eof(). So, to list a file from line 20 we can use:
while (<>)
{
print if 20..eof
}
Python people refer to Perl as 'the dark side' - geddit?
while (<>)
{
print if 20..eof
}
#!/usr/bin/perl
use strict;
use warnings;
use Time::Local;
sub str2time
{
my $in = shift;
my ($hour, $min, $sec) = split (/:/, $in);
my ($mday,$mon,$year) = (localtime(time))[3,4,5];
my $retn;
# timelocal throws an exception on an invalid date/time
eval {
$retn = timelocal($sec,$min,$hour,$mday,$mon,$year);
};
return $retn; # undef on error
}
print "Please enter the first time in HH:MM:SS format: ";
my $intime = <STDIN>;
chomp $intime;
my $time1 = str2time($intime);
die "Invalid time: $intime\n" if !defined $time1;
print "Please enter the 2nd time in HH:MM:SS format: ";
$intime = <STDIN>;
chomp $intime;
my $time2 = str2time($intime);
die "Invalid time: $intime\n" if !defined $time1;
my $diff;
if ( $time1 > $time2 ) {
$diff = $time1 - $time2
}
else {
$diff = $time2 - $time1
}
my $mins = int($diff / 60);
my $hours = int($mins / 60);
$mins = $mins - ($hours * 60);
my $secs = $diff - ($mins * 60);
printf "Difference: %02d:%02d:%02d\n", $hours,$mins,$secs;
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <sys/inotify.h>
void get_event (int fd, const char * target);
void handle_error (int error);
/* ----------------------------------------------------------------- */
int main (int argc, char *argv[])
{
char target[FILENAME_MAX];
int result;
int fd;
int wd; /* watch descriptor */
if (argc < 2) {
fprintf (stderr, "Watching the current directory\n");
strcpy (target, ".");
}
else {
fprintf (stderr, "Watching %s\n", argv[1]);
strcpy (target, argv[1]);
}
fd = inotify_init();
if (fd < 0) {
handle_error (errno);
return 1;
}
wd = inotify_add_watch (fd, target, IN_ALL_EVENTS);
if (wd < 0) {
handle_error (errno);
return 1;
}
while (1) {
get_event(fd, target);
}
return 0;
}
/* ----------------------------------------------------------------- */
/* Allow for 1024 simultanious events */
#define BUFF_SIZE ((sizeof(struct inotify_event)+FILENAME_MAX)*1024)
void get_event (int fd, const char * target)
{
ssize_t len, i = 0;
char action[81+FILENAME_MAX] = {0};
char buff[BUFF_SIZE] = {0};
len = read (fd, buff, BUFF_SIZE);
while (i < len) {
struct inotify_event *pevent = (struct inotify_event *)&buff[i];
char action[81+FILENAME_MAX] = {0};
if (pevent->len)
strcpy (action, pevent->name);
else
strcpy (action, target);
if (pevent->mask & IN_ACCESS)
strcat(action, " was read");
if (pevent->mask & IN_ATTRIB)
strcat(action, " Metadata changed");
if (pevent->mask & IN_CLOSE_WRITE)
strcat(action, " opened for writing was closed");
if (pevent->mask & IN_CLOSE_NOWRITE)
strcat(action, " not opened for writing was closed");
if (pevent->mask & IN_CREATE)
strcat(action, " created in watched directory");
if (pevent->mask & IN_DELETE)
strcat(action, " deleted from watched directory");
if (pevent->mask & IN_DELETE_SELF)
strcat(action, "Watched file/directory was itself deleted");
if (pevent->mask & IN_MODIFY)
strcat(action, " was modified");
if (pevent->mask & IN_MOVE_SELF)
strcat(action, "Watched file/directory was itself moved");
if (pevent->mask & IN_MOVED_FROM)
strcat(action, " moved out of watched directory");
if (pevent->mask & IN_MOVED_TO)
strcat(action, " moved into watched directory");
if (pevent->mask & IN_OPEN)
strcat(action, " was opened");
/*
printf ("wd=%d mask=%d cookie=%d len=%d dir=%s\n",
pevent->wd, pevent->mask, pevent->cookie, pevent->len,
(pevent->mask & IN_ISDIR)?"yes":"no");
if (pevent->len) printf ("name=%s\n", pevent->name);
*/
printf ("%s\n", action);
i += sizeof(struct inotify_event) + pevent->len;
}
} /* get_event */
/* ----------------------------------------------------------------- */
void handle_error (int error)
{
fprintf (stderr, "Error: %s\n", strerror(error));
} /* handle_error */
/* ----------------------------------------------------------------- */
Multi-threading has been around a long time. I first heard the term in the mid-1980s when discussing how ICL were going to host UNIX on VME. The first real implementation I saw was on Apollo NCS, a system that had many innovative features. ICL, VME, and Apollo have all gone, victims of acquisitions. Threads remain.
Multi-threading hit the mainstream with Windows NT, the system was built on it. The consensus around us UNIX hackers was that Microsoft had to encourage threads because their processes were so inefficient - no fork/exec you see. Probably utter twaddle; you know what UNIX hackers are.
Threads brought synchronisation problems. Of course they did. System programmers were no strangers to this type of issue, just the context of threads was new(ish). Way back when, on ICL VME, all we had were "test and set" and "decrement and set" instructions that were atomic. When I were a lad we had to build our own primitives, there was a particularly handy instruction that let you not only raise an interrupt (event/signal, whatever) but allowed you to send a two-word data block with it. Kids of today … don't know they're born… forty miles 't pit… etc.
I got to write real synchronisation primitives when I did the VME port of the MIMER RDBMS in the early '80s. There is nothing like having to write the damn things to understand how they work. I did not design them, I hastily add - that was done by some egg-head at
First rule when writing co-operating threads: things only go wrong at the worse possible moment. And that is usually after the thing has gone into production.
The Windows APIs are fairly easy to use, certainly compared to knitting your own. The main wrinkles in using them are a few peculiarities with the C/C++ runtime-library. I find it amazing that so many system engineers insist in using CreateThread instead of _beginthreadex. Back in Visual Studio 2.0 this was understandable, even I did it. The documentation was, um, "challenged". Now, with the MSDN, there is no excuse, the problems are well documented. Still people insist on using the wrong API. My theory, for what it is worth, is that a call to _beginthreadex, with its associated casts, looks messy on the screen, surrounded as it is by unrivalled elegance (sic). CreateThread looks good, _beginthreadex is ugly. For wotsit's sake! A thing of beauty with a memory leak is bad code, and I don't care what it looks like. Humph.
Still, you thought that was ugly? Try finding the thread-safe RTL functions in pthreads. Threads had to be retro-fitted to UNIX. Many fought against it, even the hero Torvold in the clone wars, but resistance was futile. Microsoft made life easy for us developers by having a whole special runtime-library just for multi-threading, ungrateful pups that we are. The pthreads implementations on UNIX have no such luxury. Instead there is a whole mess of different functions that are re-entrant with the _t suffix. Bye-bye portability. Finding which functions these are is a bit hit and miss, sometimes they are not in the man pages, and the standard only lists minimum requirements. Try teaching Condition Variables to a class already spaced out by mutxes. The word "predicate" makes their eyes glaze over. The fixed grin is the give-away: "Gone, solid gone", as Baloo would say. I'm sure Kipling was a coder, who else would write a whole poem about a conditional statement?
use AModule;
use BModule;
BEGIN {
print __PACKAGE__." BEGIN block\n";
}
use AnOther;
$syntax_error = 42
print "Starting main program\n";
print "Ending main program\n";
AModule BEGIN block
AModule main body
BModule BEGIN block
BModule main body
main BEGIN block
AnOther BEGIN block
AnOther main body
syntax error at main.pl line 18, near "print"
Execution of main.pl aborted due to compilation errors.
BEGIN {
if ( defined $ENV{TESTLIB} ) {
unshift @INC, $ENV{TESTLIB}
}
}
BEGIN {
print __PACKAGE__." BEGIN block\n";
my $code = sub { print "\@INC code\n" };
unshift @INC,$code;
}
use AnOther;
main BEGIN block
@INC code
AnOther BEGIN block
BEGIN {
print __PACKAGE__." BEGIN block\n";
my $code = sub {
my (undef, $loading) = @_;
my ($package, $filename, $line) = caller;
print "Loading $loading from $package\n"
};
unshift @INC,$code;
}
use AModule;
use BModule;
use AnOther;
main BEGIN block
Loading AModule.pm from main
AModule BEGIN block
AModule main body
Loading BModule.pm from main
BModule BEGIN block
BModule main body
Loading AnOther.pm from main
AnOther BEGIN block<>
Of course, further diagnostics could be added, like filename, line, and date/time. I'll leave that to you.
Q. So, @INC is more powerful than its sister %INC, which is just used for diagnostics.
A. Err, no. %INC is used by perl to see if a module is already loaded.
Q. And how is that useful?
A. We can force a module reload by removing its entry from %INC. Consider:
In one part of our code we want to force a different version of a module to be loaded (don't ask why).use strict;
use warnings; # DON'T use -w
use A;
use MyB;
use C;
A::mysub(); # Original modules used
delete $INC{'A.pm'}; # Force perl to reload
unshift @INC,'mydir'; # Change @INC
{
no warnings 'redefine'; # No 'redefined' warnings
require 'A.pm'; # Reload module
}
A::mysub(); # Module in 'mydir' used
Work it out yourself!