« September 2008 | Main | November 2008 »
October 31, 2008
Remember your units

I remember one of my maths teachers at school - a certain Mr Shaftesbury - who despaired of me. I think he was the one who told my parents I would never be able to do even simple arithmetic.
I was reminded of him a couple of hours ago when our order for 4 carrots turned up as 4 kilograms of carrots... for he was always one to mark down answers, quite dramatically, if you failed to show your workings as to how you got to an answer, or you failed to state the units. The workings - well .. "it's obvious" were often my words (and it was to me), but in hindsight his lesson on stating the units - as has been shown by today's experience - was clearly well thought through and well intended.
Thinking back, I suspect that Mr Shaftesbury had me down as a cheat when I provided just the nubs of the answer - but in fact that wasn't the case. It was always somewhat more important to me to have the answer than to be too bothered by how I reached it, and it was somewhat more important to me to spend my time doing other things and leaving mey homework to be rushed (and so looking distinctly un-neat) on my way in to school.
Posted by gje at 05:29 PM | Comments (0)
Related topics: via article database
More about Graham Ellis of Well House Consultants
Reactive (dynamic) formatting in Perl
If you want to format your data neatly in columns, you can use sprintf or printf to do so if you're using a fixed width font. A format of "%20s", for example, calls for a string that's 20 characters long and will be trailing space padded ... except ...that figure "20" is a minimum width, and if your text is longer, the output line will also be longer!
There are two possible solutions you can apply. The first is to use a format of the form "%20.20s" which says "make it 20 wide and TRUNCATE the string to 20 characters if it's longer" ... which might be fine in some circumstances, but eliminate vital data in others. The second solution is to use dynamic formatting. Here's how it works
a) Look through all the data that has to go into a particular field, and note the longest string's length
$longhost = 1;
foreach $host (keys %counter) {
if (length($host) > $longhost) {$longhost = length($host); }
}
b) Use the variable that contains that longest string's length within the format string:
printf("%-${longhost}s ",$host);
There's a complete program showing this (with comments too, to explain things like the ${var} notation) here.
Further new samples this morning ...
An introductory example to hashes
Modifiers and comments in Perl regular expressions
Looking up data in a file from a web page
Posted by gje at 07:25 AM | Comments (0)
Related topics: via article database
Useful link: Perl training
October 30, 2008
Seven new intermediate Perl examples
From the "learning to program in Perl" course I'm running this week, I am pleased to present seven new examples ... written during the course, in front of the delegates, to show them NOT ONLY how the code works, BUT ALSO how a programmer will develop such code.
Lists and Context
* If you use an @abc, you mean the WHOLE of a list
* If you use $abc[10], you mean a scalar member of a list
* If you use $#abc, you mean the top index number of a list
* If you refer to a list IN A LIST CONTEXT you mean all elements
* In a SCALAR context, you mean the NUMBER OF ELEMENTS in the list
* In a DOUBLE QUOTE context, you mean a string of all element ...
... linked with a space between each of them
See source code at A demonstration of lists and context
Handling command line options with getopts
The getopts sub (in the Getopt::std module that's supplied with the Perl distribution) lets you process command line parameters (from @ARGV) ... filtering out options into flag variables without the need for you to write (and maintain) that code yourself.
See source code at getopts - command line handling in Perl
UK Postcode matching in Perl
This is a testbed program to validate UK postcodes and also to extract the various key elements into other variables.
The section of a postcode up to the mandatory space is known as the "in" as it's inbound to a sorting office, and the section after the space is known as the "out" as it's used to sort at the sorting office into individual post staff delivery runs.
I have used the \b boundary condition in this code - I did NOT want to anchor to start or end of line, but neither did I want to match postcodes that start within a word. \b (word boundary match) is a happy compromise.
See source code at Regular Expression - match and extract from a UK postcode
Running another process on a pipe
If you use backquotes, a command is run on your computer as a separate process and WHEN IT IS COMPLETED, you'll get the results back. If you want to read from the other process as it runs, you can open a piped process instead - that's using open with a pipe character at the end of what would normally be the file name, but is now the command to run your extra process in turn.
See source code at piping a ping into your perl
Splitting Money many ways
Scenario - You have 21 nieces and nephews, and you're going to spend a certain amount of money on them for presents - let's say a total of 1000 pounds. But some of the nieces and nephews may not be in favour (for example, you were not thanked for last year's gift) so you'll split their share amongst the others.
Produce a table, nicely formatted, showing how much money you'll be spending on each child depending on how many are in favour.
See source code at Formatting money and other text in Perl
Single, Double and backquoted strings
In Perl, you can write ...
* A literal string in single quotes
* A string in which \ $ and @ are expanded in double quotes
* An operaring systems command to be run in backquotes
and in each case, the result will be returned to you as the result of the operation if you want to save it into a variable.
If you really want a double quote character within a double quoted string, you can always add an extra \ in front of it - but that facility is NOT similarly available to you if you want a single quote in a single quoted string. So you have to use the alternatives ...
* qq followed by any non-alphanumeric delimter of your choice gives you a double quoted string
* q followed by any non-alphanumeric delimter of your choice gives you a single quoted string
* qx followed by any non-alphanumeric delimter of your choice gives you a shell executed command
Finally, you can write multiline strings in what are know as "here" documents, where the delimiter is a complete string and must occur further down on a line ON ITS OWN (no ;, no spaces) to indicate the end of the block.
See source code at single double and backquotes in Perl
Tiny code in Perl
The code in this example uses the -n option which implies that it runs within a loop that reads each line in turn from a file named on the command line and stores it in the "default input and pattern matching space" a.k.a. $_ ...
It's open to debate whether or not coding in this way is good practise - my personal view is that it's great for occasional utilities where you just need to quickly filter a data file on one or two occasions, but it's not a good idea for long term coding where you need to have maintenance in mind.
See source code (but it's very short indeed!) at using an implicit loop with -n
In all these new examples, I have added an __END__ to the end of my source code to stop the Perl interpretter at that point, and then added in some sample output so that you can see what the code produces when it runs. There are plenty of other resources / samples accessible from the sample source pages too.
We have a public Using Perl on the Web and a public Perl for Larger Projects course both coming up just before Christmas [2008], with space available. Both courses will run again in 2009 ... please follow the links in this paragraph for the next dates if you've missed Christmas!
Posted by gje at 07:46 AM | Comments (0)
Related topics: via article database
Useful link: Perl training
October 29, 2008
Wiltshire at dawn - the tourist trail
With the clocks going back at the weekend, it's no longer possible for us to show delegates on our courses some of the lovely Wiltshire countryside after we're done with training for the day. Which is a great shame when there are lovely places like Lacock Abbey around. So this morning ... we went out before breakfast to see a few of the sites at dawn.
Wiltshire is all a'bustle with commuters in the hours before 9 a.m. (and few of them can use public transport, which is inadequate!) so this morning's tour was very much a case of 'llok for the quiet places" to avoid 90 minutes of A350 traffic jams. So here we are, off the normal tourist trail, in Calne - well known as the former home of Harris's sausage factory, with the heart being ripped from the town when it closed.
And on to Avebury stone circle, with the road passing through the middle, and the Red Lion - said to be "the only pub in the world within a stone circle". Even here, I had to wait a while to snap a picture that wasn't a line of cars heading up from West Wiltshire to Swindon for work.
As it grew lighter, the pictures got better - here's a further picture taken on the Marlborough Downs, and our guest on his second trip (ever) to England had a chance to take in a little of the countryside. He tells me that his first trip was a short stop at Heathrow as he transferred to a flight to Iceland ... and that he's got a far better impression this time.
Posted by gje at 11:28 AM | Comments (0)
Related topics: via article database
October 28, 2008
Camera with night vision, youth with no vision
I'm rather pleased with my current digital camera - it's able to take good evening and night shots of the sort I would scarcely have thought possible a couple of years ago.
This image is at Westbury Station last Sunday evening, when the Portsmouth to Cardiff trunk service had been replaced by a bus from Westbury all the way to Bristol - here, the train from London pulls in to a platform that's already crowded with passengers awaiting it, and also awaiting a Portsmouth train that's due to start from the same platform five minutes later. I was down at Westbury collecting a visitor who should have been able to connect into the 19:35 to Melksham - except that it had been replaced by a bus two buses - one to Trowbridge, and one on to Melksham.
Here's another picture at night - Melksham station earlier this month, with the 19:11 to Southampton approaching. Again, taken with available light on the marvellous little camera that - it seems - others can't believe can be so good. For I stand accused of the heinous crime of using flash to photograph a moving train ... which is against the rules as it can distract the driver and he might steer the train off the road. No - there has to be something wrong with that explanation!
Actually, it's not the first time that I've been (falsely) accused of breaking the rules ... and I'm sure it won't be the last. And frankly it makes me both rather sorry for the people who make the assumption that a rule was broken ... and also rather sure that the rule is probably one that THEY are in the habit of breaking themselves - for why else would they assume that other do?
I guess I also feel a bit sorry for the lad - a bit sympathetic for him - as he's quite young, just trying his wings for the first few times out of the nest, and coming in to one or two rather abrupt collisions with the ground, taking advise and being led by some of the other fledglings.
Should you wonder at the quietness of Melksham Station in the previous picture, I'll agree with you. You really can't expect anything else when the 19:11 is the first southbound service after the 06:40 - there simply aren't enough and rightly timed trains to make the service attractive. But then this final picture - at Swindon just a couple of hours after the Westbury picture - makes you realise that - even in a supposedly busy place - there are dramatically quiet times.
P.S. No flash here, either!
Posted by gje at 09:27 PM | Comments (0)
Related topics: via article database
October 27, 2008
November and December Public Course Schedule
It's only a couple of days since we turned the clocks back, but already my weekday time is fully spoken for up to Christmas - with bookings on all of these public courses so they're guaranteed runners (remember - we never cancel a course once you've booked it!)
| November 2008 | |
Python Programming [Link] | Monday 10 November 2008 to Wednesday 12 November 2008 |
The MySQL Relational database [Link] | Thursday 13 November 2008 and Friday 14 November 2008 |
Deploying Java applications on Linux and Unix [Link] | Monday 17 November 2008 to Friday 21 November 2008 |
Linux Basics [Link] | Monday 17 November 2008 |
Linux Administration [Link] | Tuesday 18 November 2008 |
Deploying Apache and Tomcat [Link] | Thursday 20 November 2008 and Friday 21 November 2008 |
December 2008 | |
Object Oriented programming with PHP [Link] | Friday 5 December 2008 |
Deploying LAMP - Linux, Apache, MySQL Perl / PHP / Python [Link] | Monday 8 December 2008 to Thursday 11 December 2008 |
Linux Basics [Link] | Monday 8 December 2008 |
Linux Administration [Link] | Tuesday 9 December 2008 |
Linux Web Server [Link] | Wednesday 10 December 2008 and Thursday 11 December 2008 |
Regular Expressions [Link] | Friday 12 December 2008 |
Perl for Larger Projects [Link] | Monday 15 December 2008 to Wednesday 17 December 2008 |
Using Perl on the Web [Link] | Thursday 18 December 2008 and Friday 19 December 2008 |
The other dates? Private courses on site in Liverpool and Cambridge ... a weekend meeting with Santa on 30th November ... acting as Maitre d'Hotel for a photography weekend ... and two private Java courses and a Ruby one here in Melksham.
Posted by gje at 11:22 PM | Comments (0)
Related topics: via article database
October 26, 2008
A few of my favourite things
"Raindrops on roses and whiskers on kittens; Bright copper kettles and warm woollen mittens ..."
Sorry - the raindrops get me all wet, and I always get caught up on the thorns of roses. Mittens restrict the hands and make me even more butter-fingered than I am normally ... isn't it great that we're all different - we all have different favourite things!
I was in Cambridge last week, running a Perl course - and someone asked me which my favourite programming language was. Now there's a tough question, but it did lead on to a demonstration - in Perl because that's what the course was - that showed the favourite things that bring people to our web site from Google. Here are the results - showing the top words for 23rd October!

$ perl search_fodder
2385 - Perl
2055 - Java
1850 - In
1844 - Php
1754 - Python
1331 - Mysql
1003 - To
880 - Example
870 - Join
739 - Tcl
Total 14416 searches and 118619 others
0.71 0.13 0 0
$
Here's the code ... showing some really very bad things (like a complete lack of comments) and some really "wicked" things where Perl is such a passed master!
open (FH,"ac_20081023") or die;
while (<FH>) {
if (/[&?]q=(.*?)[&"]/) {
$ss = $1;
$seaches++;
@words = split(/\++/,$ss);
foreach $w (@words) {
$w =~ s/%(..)/pack("C",hex($1))/eg;
$sw{ucfirst(lc($w))}++;
}
} else {
$others++;
}
}
@words = sort {$sw{$b} <=> $sw{$a}} keys %sw;
foreach $word(@words[0..10]) {
print "$sw{$word} - $word\n";
}
print "Total $seaches searches and $others others\n";
@taken = times();
print "@taken\n";
You'll note ...
• Use of $_
• Regular expressions to decode URLs
• Sparse matching in a regular expression
• A hash of counters
• List Slice syntax to report just "top 10" results
• Anonymous sort subroutine
• A timer to tell me how much resource was being used.
If you can identify each of those, great ... if you need help in identifying them, perhaps I should run a Perl Programming Course for you!
Posted by gje at 12:45 AM | Comments (0)
Related topics: via article database
October 25, 2008
Volunteer v Employee - a skewed balance? (FSB)
"But it's not sexy" ... a reason advanced for something that should be newsworthy, or worthy of attention, but hasn't made the headlines.
Take, for example, the relationship between volunteers and employed staff within charities and other non-profit organisations. Whereas employed staff has many a great number of rights and protections under law, volunteers have next to none ... and if there's a falling out between the two elements, there's something of a trend for the volunteer to be treated shabbily or shamefully, for fear of the employee taking a case against the employer. I have heard of long-standing volunteers in charity shops being told by a new (employed, paid) store manager that their services are no longer required and whilst I can't speak for the particular cases, there's a pattern to the harshness and effect on the volunteer - and the customers who have grown to know that volunteer - that gives serious cause for concern.
But one particular case that I can talk about with some first hand knowledge is the local region and branch of our Federation of Small Businesses. The FSB touts itself as being a "Member Lead Organisation" - though I note that those words are less visible than they used to be - and states its mission statement as: "To be and remain the largest and most effective organisation promoting and protecting the interests of the self employed and small business owners within the UK". But the more active of those business owners who volunteer to assist at a local and regional level can find themselves shabbily treated if they dare to say "boo" to a goose - or rather to one of the Federation's employees.
Let me tell you a little about the case. In May 2007, Mrs X was suspended from her roles as branch and regional chairman after accusations were made against her by an employee. Her resignation from the National Council was also required, based on a vote at which - it later transpired - eligible voter(s) were debarred by not being given voting papers. At the tail end of 2007 / start of 2008, at a branch EGM and AGM, Mrs X was voted back in as the branch chair, but was immediately suspended from the role once again. Only in May, 2008, was the case referred to the Federation of Small Business's Disputes and Disciplinary Committee who met in Bath at the beginning of this month, and completely cleared Mrs X of the matters for which she was originally suspended. However, it's not within the remit of the committee to lift the suspension, so Mrs X remains suspended to this day - for something that she's been cleared of. It gets worse - I understand that the rules concerning who is eligible to stand for office next year were changed in Spring 2008, and nomination papers in which Mrs X was seeking the local chair once again at the forthcoming AGM have been rejected because (as a suspended officer) she is not eligible to stand for re-election.
Mrs X has been a rock of the local FSB branch and region over recent years; in her absence, with two other committee members suspended too (one similarly cleared, one resigned as she couldn't go all through the inevitable pressures this has brought on) and with the local region also suspended, local services to members have crumbled. Remaining committee member volunteers (I remained on the committee until the AGM about a year ago) found our ability to plan anything such as even simple networking events hamstrung by requirements that seemed designed to frustrate. And the cost of the whole business must be tens of thousands of pounds - which no doubt comes out of the FSB's bank account, the major contributor to which is people like myself - an ordinary FSB member.
I - still - need to be very careful indeed what I write concerning employees. But I can tell you that Mrs X had an excellent working relationship with the predecessor of the employee who made the accusations, with the two of them working together very much as employee and volunteer should work in such an organisation. Where the right people are in the right roles ... my goodness ... an organisation such as the FSB can / should do so much good, but alas that's not the case at the moment [for whatever reason]. Let's hope that the D&D Committee's report, which highlights many organisational problems, is fully taken to heart and that the FSB can sort out its problems and get back on track.
((If you're a local FSB member reading this - North and West Wilts Branch or Western Region - and aren't fully in the picture, please feel free to email me - graham@wellho.net. I think that FSB members, who pay for services that have clearly been diverted over the past 18 months have a right to further information, but it's not right or appropriate for that information to be published while the final elements are still being - so s-l-o-w-l-y - played out))
Update - November 2009. This article has recently been brought to my attention as being potentially biased, incomplete or in error. I am happy to make necessary additions to complete the story or reflect other views, and to correct any error of fact. See here
Posted by gje at 11:20 AM | Comments (0)
Related topics: via article database
Three Seasonal Pictures



I've not labelled them individually, as each of them stands as a picture on its own. But if you want to know more, the first is Oliver's Castle, near Devizes, Wiltshire and the second was taken in Oxford a couple of weeks ago. The third picture shows me between a chap who's seeking a new job at an age when most of us will be thinking of retirement, and a woman who's currently one of the most expensively dressed in the world. Taken at Washington (Dulles) Airport - in reality (of course), they're just cardboard cut-outs.
Posted by gje at 09:22 AM | Comments (0)
Related topics: via article database
October 24, 2008
Well structured coding in Perl
Write a small code utility - a few lines - and you can simply start at the top and work through to the bottom. But as the code increases in length, you're going to want to take out common code and put that code into named blocks that can be re-used. Extending this technique, you can break all your code into named blocks - which can be arranged in tree. And this is a structured program.
With structured programming, your main code doesn't exceed a page (deliberate woolly definition of what I mean by a page!) and calls a series of other major blocks of code, each of which has the same maximum size. This major blocks then call other less major blocks, and so it goes on. What does this technique give you
• easily readable sections of code - especially if you write each of them to good standards/
• The ability to modify you application easily by adding in and taking out chunks of code - it's like working with Lego bricks rather than as an organ transplant surgeon
• A clear scheme under which you can test the code segment by segment if need be, writing test harnesses for each part, dummying sections in if you need to
• The ability to store commonly used elements into seperate code files so that they can be re-used across a lot of programs.
But when you're developing code it is - I admit - sometimes hard to see where the stucture should lie - initial advise is if you are tempted to copy and paste a block of code, thing twice and make it a named block if you possible can. Further advise, though, where you're not likely to have such initial high re-use is write pseudo code to start with - the application being just a few comment which turn quickly into calls in the langauge of choice and are then filled in with a few extra surrounding variables for transferring / passing data.
Yesterday, I wrote an example along these lines in Perl. Of all the languages we teach, Perl is perhaps the easiest one for people to write code that's a real "dog's dinner" that's impossible to follow later - "write only coding" is another name for it. But in this example, you'll see that you can quickly get an idea of what's going on, even from just the main code:
# Read the data
@p_records = suck("../requests.xyz") or die ("No data");
# Find the Perl records and produce a title and report
@rin_order = &massage(@p_records,"Perl");
titleit("People who know Perl");
blow(@rin_order);
# Find the Java records and produce a title and report
@rin_order = massage(@p_records,"Java");
titleit("People who claim to know Java");
blow(@rin_order);
In this example, I wrote the named blocks of code (know as subs in Perl) into the end of the same file ...
# -----------------------------------------
use strict;
sub suck {
my ($infile) = @_;
@_ == 1 or die ("Bad Call to suck");
print ("$infile\n");
open (FH,$infile);
<FH>;
}
sub massage {
my (@records) = @_;
my $skill = pop @records;
grep(/\b$skill\b/,@records);
}
sub blow {
foreach (@_) {
my @parts = split;
printf ("%14s ",$parts[0]);
foreach my $skill (@parts[1..$#parts]) {
printf("%10s ",$skill);
}
print "\n";
}
1;
}
sub titleit {
print "\n";
print $_[0],"\n","-" x length($_[0]),"\n";
}
Some further things to note ...
• an absence of global variables within the subs - everything is passed in and out to make the code elements work cleanly and clip together in an obvious way. This absence is forced / validated by the use strict in the code.
• the hiding of more complex logic within the individual subs - there's no need for the top level programmer / person re-using the subs to get involved with the detail of what goes on internally - just like you don't have to know how to drive a train to travel on one. (This is known as "encapsulation")
• the LACK of comments in each sub. This is very arguable - each sub should really have a short note of what it does, but there is certainly no need to document each and every line!
• the use of spaces, and good, consistent, variable names to supplement the understandability of the code (you could consider these to be "comments which are not comments")
I'm teaching another Perl Course next week, a further one at the start of December (that's a private course so you won't find it on the schedule) and then further ones early next year. After being slightly unfashionable for a while (as we wait and wait for Perl 6), it seems that many people have given up waiting and are finding that Perl 5 remains pretty darned hard to beat. I agree - fabulous language - you can do a lot in a very little code, even if it does require strong management to avoid the "dog's dinner" look.
Posted by gje at 06:40 AM | Comments (0)
Related topics: via article database
Useful link: Perl training
October 23, 2008
Perl and Blackberries
"Of course people will use Perl - it's free". No - whilst Perl is freely distributed [under license], that's not the sole reason that people use it. Blackberries, growing in profusion on the roadside at this time of year are free, but that doesn't mean that every motorist going past is going to stop and pick them.
People use Perl because it's a darned good language! I used to say that I could write - in a day - code in Perl that would take me a week in C. Actually, I've changed what I say over the years as I've got to know Perl better ... I'm now saying that I could write in a morning the code that would take me a week in C. Yes - truly claiming a 10:1 improvement in productivity. And the same can be said for certain other languages such as PHP, Python and Ruby. I'll stick with "a day" for Tcl and Lua - where there's longer code to write and / or not such a thorough set of standard functions in what are designed to be much smaller and tighter languages, and I'll say "a couple of days" for Java coding.
See Heaven's Gate for the blackberries in context, and here for Perl programming.
Posted by gje at 11:47 PM | Comments (0)
Related topics: via article database
Useful link: Perl training
October 22, 2008
Pictures from a delegate
Conversation from last week: "I'm taking pictures because I've never been in this area, but why are YOU taking pictures" - a delegate on my course. "Because it's a beautiful area and I take a lot of pictures" - my reply. Mikkel has sent me a link to his pictures, and I told him while he was with us that I would like to share the link. His pictures are here and I think they're very good!
(The picture on the left of this page is one of mine, from my Bath page - I didn't want to hotlink any of Mikkel's on to here knowing how upset I've been know to get with people nicking our bandwidth!)
Posted by gje at 06:57 PM | Comments (0)
Related topics: via article database
October 21, 2008
Daisy the Cow and a Pint of Ginger Beer
One of the trickiest aspects of learning for newcomers to programming is to know when to split out parts of their code into named blocks. Newcomers can easily see that it's a good idea - as it means that code can be tested in smaller chunks, and that code can be shared (reused) - but it's not always obvious just how the division / split should be done.
Here's a rule of thumb ... if you find yourself repeating something, then it's probably an excellent candidate to be a named block of code. Sometimes there's a counter-comment made - "Yes, but I have had to alter the copy so in the end the code isn't duplicated", to which I'll reply the places you have to alter the copy are telling you which parts of the named block of code are going to be passed in as parameters, or back as return values
From today's Perl course, here is an sample application that reads a width and a height from the user, and multiplies them together to get the area of a rectangle:
use grahamslib;
$running = "Third part";
($width) = getpval("Width");
($high) = getpval("Height",20);
$area = $width * $high;
print ("The area is $area ($width x $high)\n");
print "Running is the $running part of Maz's event\n";
The code looks short and clear enough, but a lot of the work is actually performed by the getpval sub which we have written into a separate file. This sub meets all the classic requirements of a good sub - it has a small number of logical inputs and outputs, it performs a single distinct task, and it's the sort of thing that'll be reused in many different programs.
Here's the getval sub, in the grahamslib module:
use strict;
sub getpval {
my ($askem,$maxval) = @_;
my $running = 1;
my $val;
do {
print "What is the $askem ... ";
chop ($val = <STDIN>);
unless ($maxval == 0 or $val < $maxval) {
print "TOOOOO Huge\n";
} else {
$running = 0; }
} while ($running) ;
($val,"Daisy the cow","Pint of ginger beer");
}
1;
There's somewhat more there than in the simple piece of code that calls the sub - and rightly more effort should be put into developing it, as it's now available for reuse in the standard library I have created. Here are some pertinent facts if you're reading the code and wondering how it works:
• The reference to "strict" is to tell Perl that all variables must be declared with my or in some other way - the highly dangerous default of a global variable is not permitted.
• Parameters are passed in via a list called @_, from which the first two elements are copied into local variables called $askem and $maxval ... if there is only one value in the call, $maxval will be empty.
• The user is prompted to input, using the string passed in as the first parameter as part of the description text that's printed.
• The value entered is checked, and if a maximum was given which has been exceeded, the sub flags an error and loops to have the data re-entered
• Finally, when an acceptable value has been read it's put into a list with a couple of other strings. Since that's the last action performed in the sub, it is this list which is returned to the calling code; programmers wishing for clarity may like to add the word return in front of the list.
• The 1; at the very end of the file is there to ensure that the code, when loaded, returns a true value. Anything that's NOT within a sub is performed as an initialisation action when it's loaded, and this code MUST return a true value - it's a feature of Perl. Without the 1; you get an error message:
Dorothy:csro8 grahamellis$ perl sboo
grahamslib.pm did not return a true value at sboo line 2.
BEGIN failed--compilation aborted at sboo line 2.
Dorothy:csro8 grahamellis$
Are you wondering about that pint of ginger beer, and Daisy the cow? Those are just two strings of text I added to the return value in the sub as I was demonstrating it to show how a list can be returned. I like my demonstrations to be fun and a bit different - to raise a smile and make learning to Program in Perl fun.
Posted by gje at 07:40 PM | Comments (0)
Related topics: via article database
October 20, 2008
String matching in Perl with Regular Expressions
Some languages used adaptive or overridden operator to perform a task depending on the operands - for example in Java, the "+" operator adds numbers, but concatenates strings, and in PHP the == operator compares numbers or strings, depending on the operand types. But in Perl 5, it's often up to the programmer to decide between a series of operators - the "+" always adds numbers and "." concatenates strings, with Perl converting the incoming data to the type needed for the operation, for example.
The need for careful choice of operator also applies for comparisons in Perl 5:
== != < <= > and >= compare numbers
eq ne lt le gt and ge compare text strings
=~ and !~ match a string against a pattern.
Matching a string against a pattern (known as a regular expression) is a very powerful feature indeed of Perl. Regular expressions originated in utilities such as grep, awk, sed and vi, and were then extended in egrep. With Perl, they have been extended even further - MUCH further - and they're at the heart of the language. It's said the imitation is the sincerest form of flattery, and you'll find Perl style regular expressions elsewhere too - in languages such as Java, Python and PHP.
Regular expressions contain many elements that you may use to match against a string, and in order to help newcomers to learn them, I divide the elements down into a series of groupings. There are literal characters that must match exactly - things like the @ of an email address. There are character groups - things like \d to match any digit. There are counts to tell the regular expression engine how many times the previous element occurs - things like {1,2} meaning once or twice. And there are anchors which let you specify whether you're looking at the beininning or the end of a string, or anywhere within it. Finally (for this intoduction) you can bracket parts of your regular expression to indicate that you want to capture parts of the incoming string that match THAT part of the expression.
It's much better explained in a table of element types, and with an example. And here's a program written to show Perl's regular expressions in use matching a British Postcode, which includes most of the elements:
=head1 Regular Expression Elements
* Anchors (or zero width assertions) - ^ $ (starts, end)
* Character groups - [A-Z], [0-9A-Z] [AEIOU] [^AEIOU]
\d \s \w \D \S \W
[[:digit:]] [^[:xdigit:]]
.
* Literal characters - X x 3 \. \[ \? \\
* counts - ? + * {2} {1,2}
* Interesting bits (or capture parentheses) - ()
=cut
while ($postcode =
if ($postcode =~ /^\s*([A-Z]{1,2})\d[0-9A-Z]?\s+\d[A-Z]{2}\s*$/) {
print "Yeah ... $1 area ...\n";
} else {
print "Nah ...\n";
}
}
Here's how that code runs:
Dorothy: grahamellis$ perl pcre
SN12 7NY
Yeah ... SN area ...
G12 6TH
Yeah ... G area ...
NPT1 6YH
Nah ...
Dorothy: grahamellis$
We run complete days on regular expressions and have many more details available on our web site. There's even a complete page on Perl Regular Expressions especially.
Posted by gje at 11:15 PM | Comments (0)
Related topics: via article database
Useful link: Perl training
October 19, 2008
30th November - Santa Trip from Melksham

On Sunday, 30th November, Santa Claus will be travelling on the train from Melksham to Swindon and back, and handing out presents to all the children. The train leaves Melksham station at a quarter past five, and will be back just before 7 O'Clock.
Tickets (7 pounds for adults and 3 pounds for children) have just gone on sale at Melksham Tourist Information Centre - open Monday to Friday and on Saturday morning - and can also be bought from me at Well House Manor from Monday, 27th October. The price includes mince pies for the adults, who will also be given a glass of wine or soft drink, and presents for the children. Prebooking is essential, as Santa needs to know who's coming!
Last year's "Santa Special" was a huge success - except that we were heavily oversubscribed and had to disappoint a lot of people who didn't book early. Picture - Santa in Swindon before he boarded the train.
This year, Santa will be with us both ways on the journey, so that he can talk to a lot more children, and we have moved the trip onto a day / time when the train won't be as busy with other crowds from Swindon. This does mean that it's very much a trip to see Santa this year, and you will not have six hours to shop (or to hand around!) in Swindon.
This trip is being organised by the Melksham Railway Development Group, of which I am a member (And I'm on the Santa Committee so I can help with any enquiries you may have!)
Posted by gje at 10:51 AM | Comments (0)
Related topics: via article database
October 18, 2008
Lua - IAQ (Infrequently Answered Questions)
Here are a handful of "one line" answers from the end of the Lua Course I was running at the end of last week
• Command line parameters in Lua are available to the program in an indexed table called arg. (Sample Program)
• Functions in Lua can look at the number and type of parameters they're called with, and can behave differently depending on what they find (Sample program showing a function that can be called with two numbers OR one table as parameters)
• Although Pattern Matching does NOT use regular expressions in Lua, it does use many of the same principles - anchors, literal characters, groups and counts. And it can provide much of the same power but in a far smaller package! (Sample program showing how a postcode is matched and vital sections extracted)
• You can find out what is in a module by looping through its table keys - because (I'm sure you've not forgotten!) everything is a table in Lua (Sample program that lists out everything in the OS module)
You'll find many more sample programs, tips and techniques in our Lua Index. If you start with our Introduction to Lua module page, you'll find some basics. And then down the right hand side of that page, you'll find links to other groups of Lua resources such as Pattern Matching and Combining Lua and C in the same program.
Posted by gje at 05:02 PM | Comments (0)
Related topics: via article database
Useful link: Lua training
Old Piles of the South West
There's a great deal of learned speculation about the construction and reasons behind Silbury Hill (See Avebury) and a lot of digging has taken place over the years to research the issue - so much so that old shafts have collapsed in recent years leading to extensive remedial works.
Yet Silbury Hill is not the only man made mound of this shape - here's another one I spotted near Midsomer Norton (See Radstock) on my way back from dropping off a delegate at Bristol Airport on Friday afternoon.
This mound is a slag heap from the Somerset Coal Field, which was an unexpected industrial outpost set in the heart of the West's countryside, and which only ceased coal production in relatively recent years. Indeed, much of the traffic on the Kennet and Avon Canal originated from the Somerset Coal Canal ... and for a time passed up the Wilts and Berks through Melksham
Perhaps Silbury Hill is just a pre-historic slag heap?
Posted by gje at 04:05 PM | Comments (0)
Related topics: via article database
Passing a table from Lua into C
In a previous article, I showed you a simple example of how you can call a function that's written in C from Lua, and a second example that extended that - passing simple parameters in to the C function, and returning results.
But it's often more complex that that - for example, you may with to pass a table from your Lua script into a C function, so that the C function can make use of a value from the table code like this:
stuff = {hotel = 48, hq = 404, town = 1}
summat = extratasks.dothis(stuff)
This isn't as easy as just passing a value, since the size of a table can vary, and Lua's dynamic memory allocation doesn't sit well, in a simple interface, with C's static model. The "trick" is to tackle it within the C code by using function calls to get (and if necessary) reset values from the table - with the data required by those function calls being processed via the Lua stack.
Here's an example of what I mean in the C code:
/* Looking up based on the key */
/* Add key we're interested in to the stack*/
lua_pushstring(L,"hq");
/* Have Lua functions look up the keyed value */
lua_gettable(L, -2 );
/* Extract the result which is on the stack */
double workon = lua_tonumber(L,-1);
/* Tidy up the stack - get rid of the extra we added*/
lua_pop(L,1);
That code retrieves the "hq" value from the table that's been passed in (called stuff in my Lua example above) and stores it into a C variable called workon ... objective achieved!
The full source code of the Lua is available here and the C source code is here.
Here's sample output from my testing of the code:
[trainee@easterton three]$ lua wrapper.lua
Lua code running ...
Violets are Blue
Table passed to humbug
Roses are Red
... back into Lua code
Values in Lua now 527 -511
Table contains ...
hq 404
town 1
hotel 48
[trainee@easterton three]$
Looking around, I have found a number of very much more complex examples of how to embed C in Lua, but nothing as easy as the 1 - 2 - 3 steps I have shown you in this article and the previous one. If you're looking to pass strings (strings in Lua are not null terminated, so differ), to iterate through a Lua table within C, or to modify a table, you'll find that covered in Lua's reference documentation. If you would like to learn more about Lua - from the basics through to the topics covered in this article - and you feel I could help you, please have a look at our public Lua Courses or ask about a private course if you're looking at more specialised needs, or if you have a group of delegates.
Posted by gje at 02:49 PM | Comments (0)
Related topics: via article database
Useful link: Lua training
October 17, 2008
Calling functions in C from your Lua script - a first HowTo
This short article shows you how to call a function that's written in C from a program written in Lua, how to write the function that's called, and how to turn it into an appropriate library and load that library. It then goes on (as a second example) to show you how to pass variables from the Lua script to the C function, and how to pass the result back.
There are a number of examples of calling C from Lua in books, and on web sites, but I wasn't able to find a simple "first steps, everything shown" example - so that's what I set out to do here
First Example. Lua calls C, which runs and returns to Lua
the Lua:
package.cpath = "./?.so"
require "fromlua"
print("hello")
cstuff.dothis()
print ("It's run da C code!")
The C:
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <stdio.h>
static int myCfunc ( lua_State *L) {
printf ("Roses are Red\n");
return 0; }
int luaopen_fromlua ( lua_State *L) {
static const luaL_reg Map [] = {
{"dothis", myCfunc},
{NULL,NULL} } ;
luaL_register(L, "cstuff", Map);
return 1; }
And the compiler instruction to build the library:
gcc -o fromlua.so -shared fromlua.c
The first two lines of the Lua code tell Lua to REPLACE the library path with .so files in the current directory. This is great for testing but you'll want to also consider library directories in a real live program.
The C function who's name is the same as the required module, preceeded by luaopen_ is run as the module is requireed, and it defines a Map which tells the interface the names of various Lua function calls, and the equivalent function name that that map to in C. In this case, the lua function dothis maps to the C function myCfunc. The map is then registered with Lua, into a table named as the second parameter to the luaL_register call.
We've now defined where the library is to be found, loaded it, and told Lua about it. All that remains is for us to call the function from the Lua. All functions called in this way return a static int ( the number of values returned) and take as a parameter a Lua stack pointer - although in this first example we return nothing (0) and do nothing with the Lua stack passed in - we just print "Roses are Red" to show we're here. And indeed the code runs like this:
[trainee@easterton one]$ lua top.lua
hello
Roses are Red
It's run da C code!
[trainee@easterton one]$
Second Example - calling C from Lua, passing values in and returning a result.
Here's the Lua code, with the additional use of parameters:
package.cpath = "./?.so"
require "luapassing"
print("hello")
value = 10
summat = cstuff.dothis(value)
print ("It's run da C code!")
print ("Values in Lua now",value, summat)
And here's the luapassing.c source code file:
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <stdio.h>
static int myCfunc ( lua_State *L) {
printf ("Roses are Red\n");
double trouble = lua_tonumber(L, 1);
lua_pushnumber(L, 16.0 - trouble);
return 1; }
int luaopen_luapassing ( lua_State *L) {
static const luaL_reg Map [] = {
{"dothis", myCfunc},
{NULL,NULL} } ;
luaL_register(L, "cstuff", Map);
return 1; }
The code is very similar, but you'll notice six additions - in the Lua:
a) We have added a parameter to the call to dothis in the Lua
b) We have added an assignment to collect a return value from the C
c) We have printed out these values
and in the C:
d) We have used lua_tonumber to collect a numeric value that was passed from the Lua to the C; you'll note that all such numbers are treated as doubles. The parameter "1" indicates 1 down - i.e. top of - the state stack.
e) We have performed a calculation (representative of something being done in the C code) and pushed the result of this back onto the Lua state stack so that it can be picked up once we have returned from the C to the Lua
f) We have changed return 0 into return 1 to indicate that one result is being returned.
Running the code ...
[trainee@easterton two]$ lua passing.lua
hello
Roses are Red
It's run da C code!
Values in Lua now 10 6
[trainee@easterton two]$
Although the calling up of C code from within Lua is not the most common of uses of Lua for the typical scripter, the question of "how do I" arose on today's public Lua course and I was very happy to put the example together. Source code (including additional comments) is available:
• first Lua example and the associated C code
• second Lua example and the associated C code
There is also a follow up article available which includes a demonstration of registering several C functions with Lua, and passing a table from Lua into C, making use of individual members of that table within the C.
Posted by gje at 06:02 PM | Comments (0)
Related topics: via article database
Useful link: Lua training
How many cups of coffee?
It's exactly two years since we opened our doors at Well House Manor for our first residential training course delegate, and moved from being just a training provider to being a provider of overnight accommodation too.
And - goodness me - how much water has flowed under the bridge since then ... or should I say "how much coffee has flowed from our coffee machine" - which had its major service / overhaul yesterday, and the engineer told me that it has provided around 7000 (seven thousand) cups. That's not all the coffee we've provided, either - as I write this note at 07:30, a breakfast meeting of around 20 people is drinking percolated coffee, and in their rooms our guests may be making use of their hospitality trays.
I haven't commented here on the current turmoil in the financial markets and the effects it's having on people, but that doesn't mean that I'm blind to the goings on. Like many people, I don't fully understand what's happening and we can't predict with any degree of certainty where it will go in general and how we will be carried along. But what we can do is listen, learn, make plans and run the business in such a way that we carry on positively - providing high quality training and excellent business accommodation into the foreseeable future. More and more at times such as these, customer service is paramount - we had a staff meeting earlier this week at which the wider picture was looked at, and I'm confident that with the great team we have we can continue to provide what our markets are looking for.
Posted by gje at 07:14 AM | Comments (0)
Related topics: via article database
October 16, 2008
Lua Course, and the Wiltshire Countryside too
With courses such as Lua Programming, our delegates come from far and wide - it's very much a niche subject, and that's why we provide facilities that are a little different to most training companies - such as our own hotel facilities.
The wide spread of our delegates also means that we'll often be introducing all the delegates on a course to the beauties of our part of the country, and perhaps even to England - and we're delighted to do that where it does not interfere with the operation of the course. The days are getting shorter now as mid winter approaches in a couple of months, so evening excursions are out (or dark!). However, there's nothing to stop us starting the course a little earlier in the mornings, and running a little later in the evenings.
Which means we can take a slightly extended lunch break, and take our visitors to see something of what there is to see here abouts. An extra half hour in the morning, and extra hour in the early evening, the normal 45 minutes for lunch ... all add well together for a couple of hours of sightseeing.
The pictures that accompany this item were taken yesterday, and show delegates at Avebury and Silbury Hill.
Posted by gje at 07:52 AM | Comments (0)
Related topics: via article database
Useful link: Lua training
October 15, 2008
Formatting with a leading + / Lua and Perl
In formatted printing, you can often use a leading "+" in the format string to force a positive sign to be added in front of positive numbers - for example "%+4d" means an integer, to base 10, 4 character positions as a minimum, right justified.
Here's an example of that, in code, in Lua
for john = -10, 10, 1 do
print (string.format("xx %+4d yy",john))
end
And here is how it runs:
[trainee@easterton o8]$ lua sf
xx -10 yy
xx -9 yy
xx -8 yy
xx -7 yy
xx -6 yy
xx -5 yy
xx -4 yy
xx -3 yy
xx -2 yy
xx -1 yy
xx +0 yy
xx +1 yy
xx +2 yy
xx +3 yy
xx +4 yy
xx +5 yy
xx +6 yy
xx +7 yy
xx +8 yy
xx +9 yy
xx +10 yy
[trainee@easterton o8]$
The same technique applies in Perl, and in other languages too.
Other leading characters:
0 - Leading zero fill
- - Left justify
Posted by gje at 11:57 AM | Comments (0)
Related topics: via article database
Useful links: Lua training, Perl training
October 14, 2008
Validating Credit Card Numbers
It's standard practise for on line bookings these days to take credit or debit card details as a booking security, and we're no exception at Well House Manor - our hotel for business visitors to Melksham, Wiltshire. There are very many security issues involved, and I am not going to describe what we can and must do behind the scenes ourselves - rather, I'm going to show you the algorithm that checks that a card number's of the correct format in PHP.
Credit card numbers are typically 16 digits long, although some such as AmEx are a little shorter. The initial digit(s) tell you what type of card you're dealing with - the code below has the current set to the best of my knowledge, but you should check - and then all the digits are taken individually and combined into what is in effect a checksum value. If the checksum comes out as an exact multiple of 10, the number is potentially valid. If the checksum does not come out as a multiple of 10, then you can be sure the number is wrong.
The algorithm used is a clever one that's designed to make it very unlikely that a simple error in giving a credit card number (such as leaving a digit out, getting a digit wrong, or transposing two digits) is very unlikely indeed to lead you to a different valid number. Only in the case of two errors of these types does the probability of an error resulting in a valid code start approaching the 1 in 10 you might expect from a random error.
<?php
/* Some test code!
$ccwrong = array("4xxx xxxx xxxx 1123","4xxx xxxx xxxx 1716");
$ccright = array("4xxx xxxx xxxx 1715","4xxx xxxx xxxx 1111");
foreach (array_merge($ccwrong,$ccright) as $cc) {
list ($type,$valid,$cz) = ccvalidate($cc);
print ("Card $cc is $type and ".($valid?"OK":"Duff")."\n");
}
*/
# Function to take in a credit card number and identify type
# also check the check digits
function ccvalidate($ccno) {
# 1. Is is the right no. of digits (allowing commonly places spaces and dashes)
$card = "";
if (preg_match('/^\s*4\d{3}[-\s]*\d{4}[-\s]*\d{4}[-\s]*\d{4}\s*$/',$ccno)) {
$card = "Visa"; }
if (preg_match('/^\s*5[1-5]\d{2}[-\s]*\d{4}[-\s]*\d{4}[-\s]*\d{4}\s*$/',$ccno)) {
$card = "MC"; }
if (preg_match('/^\s*6011[-\s]*\d{4}[-\s]*\d{4}[-\s]*\d{4}\s*$/',$ccno)) {
$card = "Discover"; }
if (preg_match('/^\s*3[47](\d\s*){13}$/',$ccno)) {
$card = "AmEx"; }
if (preg_match('/^\s*3[068](\d\s*){12}$/',$ccno)) {
$card = Diners; }
# 2. Does the checksum work out?
# Get rid of none-digits
$ccno = preg_replace('/\D/','',$ccno);
$checksum = 0;
for ($i=strlen($ccno)-1; $i>=0 ; $i-=2) {
# Last digit, and alternate digits before it
$checksum += $ccno[$i];
# Other digits
if ($i) {
$digit = 2 * $ccno[$i-1];
$checksum += ($digit < 10) ? $digit : $digit-9;
}
}
return (array($card,$checksum%10 == 0 && $card != "",$checksum));
}
/* Notes
1. Debit cards - Maestro - 18 digits
http://web-usability-expert.com/2007/08/06/uk-debit-and-credit-card-validation/
2. Credit cards
http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CC70060A01B
*/
?>
Online booking starts with https protocol rather that http as you'll find if you use our booking systems. This is one of my few bits of code that I am *not* going to put in my "demo" directory for you to try out - as that would be starting to teach you insecure ways by example.
Our PHP Techniques Workshop does cover aspects of accepting credit and debit cards online, and you can book hotel rooms in Melksham and public training course places via our sites. If you're looking for a private course, there are so many ways that we can tailor our training that we want to talk about your requirements before you book, so we don't have a completely automated, human intervention free, system.
The illustrations with this post show bedrooms 4 (top) and 3 (lower) at Well House Manor, where we offer accommodation for visitors to the town of Melksham. Our facilities are designed for the business traveller, but others are welcome too - all rooms are double or twin (but are usually let for single occupancy), there is internet access available 24 x 7, plenty of power points, large screen TVs with some 50 channels ... all rooms are en suite, there's tea, coffee and soft drinks available all day, every day ... and all these things which are often extras are included in the price, as is a breakfast of freshly squeezed orange juice, fruit, cereal, yoghurt, bread, toast and croissants, ham and cheese, jams and marmalade.
Posted by gje at 10:40 AM | Comments (0)
Related topics: via article database
October 13, 2008
Job application
From my email
|
Subject: Application for any post.
Dear Sir/Madam; I am writing in response to the job vacancy announcement of the above mentioned post. The position requirements and my skills are a perfect match. As you'll see on my enclosed resume, I have the educational background, professional experience, and track record for which you are searching. In addition, I am motivated and enthusiastic, and would appreciate the opportunity to contribute to your firm's success. I can promise that meeting with me will not be a waste of your time and I will make myself available at your convenience, during or outside of normal business hours. Sincerely, Mustafa Phone No: +93 (0) 799 xxx xxx |
I think I'll give it a miss, Mustafa, without even opening your enclosure which claims to be (and actually might be) a C.V; at the same time, I'm trying to picture the applicant who considers himself fit for any post, and is so sure about it that he feels it will be worth my while calling him on his phone in Afghanistan about it.
Posted by gje at 03:00 PM | Comments (0)
Related topics: via article database
Oxford in Pictures
Posted by gje at 08:13 AM | Comments (0)
Related topics: via article database
Alfred the Great
Yesterday, we visited Alfred the Great, who sits cast in stone in the centre of Wantage in Berkshire.
OK - the visit was really to Oxford, but we passed over the Downs from Marlborough through Axford and Ramsbury, Membury and Lambourn, Wantage and Frilford on the way to give our international visitor something of an impression of the countryside that straddles Wiltshire, Berkshire and Oxfordshire.
Wantage is a town I have passed through many times on my commute to Harwell, near Didcot, where I worked for a number of years, and indeed I used to be able to tell you which was the best chippie in the town, and find a quick evening meal there that didn't break the bank. That's now so many years ago, though, that my information would be of only historic value, I'm sure ... even though I was already giving Perl Programming Courses in those days. It shows how in some ways things haven't changed - but in many other ways they have; although I'm still doing Perl courses and can claim longevity on one hand, and being able to claim that all the examples I used in those days should still work, I can also tell you that I know of only one example - out of several hundred - that has survived without a major update.
Of course, Alfred the Great looks rather less majestic, impressive, isolated when you see him set amongst the traffic in the centre of Wantage, and it's very much the whole that counts to give the place its character. Thus with Perl - no one feature in isolation makes it a great language; it's "eclectic" taking many things from many sources, and it's the whole picture that makes the place as it does at Wantage.
See here for some more of my pictures of Wantage. I have so many excellent Oxford pictures that they're waiting for a separate follow up thread and page!
Posted by gje at 07:44 AM | Comments (0)
Related topics: via article database
October 12, 2008
Next in the sequence - courses next year (2009)
Here's a sequence of numbers. 3, 7, 7, 4, 2, 6, 4, 1, 5. What are the following three numbers?
Quite an interesting puzzle, but it's a sequence of numbers I came across this morning ... and the following three were 3, 7 and 5 I'll tell you the trick of the sequence at the end of this article!
I have been putting together the diary for our 2009 courses - it's on line in the form of a course listing here and as a calendar here. There are also individual course descriptions which show the dates from the current time through to next summer:
Perl Programming
Perl for larger projects
Using Perl on the Web
Technology background forPHP
PHP Programming
Object Oriented PHP
PHP Techniques Workshop
Tcl Programming
Tcl - the Tk Toolkit
Deploying LAMP applications
Linux Basics
Linux Admin
Linux Web Server
Deploying Apache httpd and Tomcat
C Programming
C and C++ Programming
C++ Programming for C Programmers
Python Programming
Lua Programming
Ruby Programming
MySQL
Bookings are now open and to encourage people to think about 2009 even before Christmas 2008, we'll honour the 2008 prices for any bookings made up until the close of business on the last day we're open this December!
The sequence I started with? The first Saturday in January is the 3rd next year, the first Saturday in February is 7th, as it is in March. In April, the first Saturday is the 4th ....
Posted by gje at 08:59 AM | Comments (0)
Related topics: via article database
23:30 bookings and midnight checkins
It's 12:30 - that's half an hour after midnight - and I'm at Well House Manor to check in guests who phoned in to book less than an hour ago. I'm always wary about taking bookings this late of an evening as we can anticipate that people are just looking for a bed on which to lay there head, and don't want to have (nor to pay for!) facilities like the internet, the large screen TV, the unlimited soft drinks, tea, and coffee which are built into our standard rate. And indeed, this evening's late arrivals (whom I got out of bed to check in) suggested I charge an amount less than a half of our normal rate on the grounds that they would "only be in the room for six hours". I carefully explained that actually a single night booking costs us more as we have to do a complete room change, but Mr and Mrs X, looking for a room after a wedding when they had probably intended to go home were slightly grumpy about it - and that may mean that they don't treat the room with the usual respect overnight.
"Breakfast at about 9" they have requested, and Chris will be on well before that to cover the breakfasts for all the rooms that are taken ... I expect my concerns are groundless and I'll come back on line tomorrow and say "no worry" ... but at times the hotel business is a worry, and I think our general policy of closing for bookings at 9 p.m. each day is a sensible one; we loose a little business, but it's from customers for whom we're not ideally suited, and we gain peace of mind and a peaceful sleep.
Posted by gje at 12:30 AM | Comments (0)
Related topics: via article database
October 11, 2008
Seend, near Melksham, Wiltshire
We're only a couple of miles from the Kennet and Avon canal - and for each of the last three evenings, in this Indian Summer, I've taken a stroll down there. Trying out my new camera in the half light, I'm going to show you some picture - this one of a heron is mediocre, I know, but some of the others are more impressive ...


Although the scene looks tranquil, that wasn't always the case here about - indeed Seend Iron works must once have been a hive of activity! [See also Seend]
And at the end of the walk, what better that to sit outside at "The Barge" ... if not to drink too many pints of Wadworth 6X, then to take in the setting sun over the canal!
Posted by gje at 06:18 PM | Comments (0)
Related topics: via article database
Web Bloopers - good form design - avoiding pitfalls
The "Web Bloopers" book that we have on our shelves is a marvellous inspiration - a "there but for the grace of God go I" reminder when we put a web site - or even just a form - together - of catches to look out for.
My thoughts came back on to this a few minutes ago as I helped Wiltshire Council with a survey about their web site, which I had visited to learn about their financial investments in Iceland (found here) and how it might effect public transport (my specific TransWilts / rail view here). But that's another story ...
I was offered a choice of how often I visit the web site:
• daily
• several times a month.
Now - I would judge that I'm there a couple of times each week ... for which there was no suitable option between those two!
I was asked how I found out about the site and given ONE option to choose from. I would love to have said "I came via Google [link from another site] where I had gone to find the link to the right place on your site" but the nearest options were:
• I knew the sight already
• I found a link elsewhere to you.
Now - which of those should I choose?
I was asked to rank various elements of the site, including navigation therein. As I only went to the page that Google pointed me to, I haven't a clue as to how the internal navigation was working today ... but the survey through my lack of an answer back in my face and insisted I answer!
It's easy - VERY easy - to stand in a greenhouse and throw stones. But I do attempt to evaluate forms I put on the web to ensure that the more crass holes have been dealt with. What do I mean? Well - here's a different example.
One of the regular hotel chains that I use when away asks if you'll arrive before or after 8 p.m.; ironically, when I'm travelling a long distance the honest answer is "don't know" as 8 p.m. is almost exactly the time that I expect to get there and before / after is a guess. Now I know why the hotel wants to know - it's because they need to know which rooms to prepare earlier and which may be late, and I applaud them (a clap with just one hand, though) for attempting to gather the data.
Learning from the problems which I have as a user of their site, I opted to include a pull-down menu on our site asking people to ESTIMATE when they would be arriving, and giving 2 hour bands. That way, the customer should not feel worried by "will they let the room go if I'm not there by 5" as it was an estimate, and if the booker is a 2 hour "slot" out as regards their actual arrival, it's no problem at all to us - we still have an excellent broad brush overview of our need to have rooms ready. And, yes, we do have a "before 3pm" and "after 11pm" options to catch the extremes and not miss out any options.
Wiltshire Council's survey - with answers forced to conform with criteria that really don't match the user's view, and fed with false data on things like navigation - may give them some information. But the detail of the results will be statistically flawed, and the thoughtful survey completer frustrated, all due to a lack of proper form and survey design.
Posted by gje at 09:33 AM | Comments (0)
Related topics: via article database
Processing all files in a directory - Perl
From this week's Perl course:
opendir(DH, ".");
while ($igot = readdir(DH)) {
next if ($igot =~ /^\.{1,2}$/);
print "igot $igot\n";
}
You'll notice that I have used a regular expression to check for files called dot and dot-dot, which are the current and parent directory, as I typically would NOT want to process each of them in my loop.
Other alternatives ... this is Perl so "There is more than one way" ... include:
@files = glob("*");
@files = <*>
@files = `ls`
but although each of these is shorter, they are not recommended for heavy directory traversal applications - in each case, they return you a sorted list of names and that sorting can be useful for a single directory, but wasteful in a heavier application that's going through a large number of directories.
Once you are traversing a directory, you can do all sorts of things - use operators such as -d to find out what is a subdirectory, and -s to find the size of individual contents, for example.
If you want to find the biggest file in or below a directory (perhaps you're running out of disc space?), we have a sample program here from our Perl for larger projects course.
Posted by gje at 07:25 AM | Comments (0)
Related topics: via article database
Useful link: Perl training
Text formating for HTML, with PHP
Do you want "normal" text that's formatted in a fixed width font, with white spaces and tabs and new line characters to have a similar appearance on a browser? The default answer of you generate a page of HTML is "tough luck", as text defaults to a variable width font, lines are squished together with multiple spaced becoming single spaces, and even new lines are treated as just white space.
You want:
/dev/disk0s3 117089712 83067248 33766464 72% /
devfs 106 106 0 100% /dev
fdesc 1 1 0 100% /dev
map -hosts 0 0 0 100% /net
map auto_home 0 0 0 100% /home
/dev/disk1 3674142 3674142 0 100% /Vol/MOS
but you get:
/dev/disk0s3 117089712 83067248 33766464 72% / devfs 106 106 0 100% /dev fdesc 1 1 0 100% /dev map -hosts 0 0 0 100% /net map auto_home 0 0 0 100% /home /dev/disk1 3674142 3674142 0 100% /Vol/MOS
How can you achieve the effect you desire? There are or have been a number of options:
a) The <PRE> to </PRE> tag pair - though even within there you need to be careful of & and < characters.
b) white-space: pre; within your CSS - but there are issues with how some versions of Internet Explorer handle that attribute
c) Specify Content-Type: text/plain in your headers, but that will turn the whole document into pure text - rather like letting the tail wag the dog
d) Setting the columns of data you see in the example above into columns of a table to achieve a display which is not identical, but has a similar readability
e) Using a fixed width font such as courier, converting spaces to special characters, and converting new lines into <br /> tags.
Take your choice - there are times that each option is a good one. If you're coding in PHP, then there's a function in the language - nl2br - that converts new lines to line breaks, and you could also use preg_replace to convert spaces into - s
Here's a sample PHP program that uses nl2br - and I have also taken the opportunity to illustrate a "here document" which allows me to add a multi line block of text within my PHP. The <<< syntax is oft overlooked ....
<?php
$line = "The Pie Shop\n25 High Street\nSalisbury\nWilts\n\n";
print ($line);
print (nl2br($line));
$haircut = <<<BALD
I used to have %colour% hair, then I went
grey and then I became hairless. With %colour%
hair, they used to call me "bushy". With grey,
they thought I was a whizz or wizzard, and now
I'm called Coot.
BALD;
$output = preg_replace("/%colour%/","ginger",$haircut);
print (nl2br($output));
When I run this from the command line, I get:
The Pie Shop
25 High Street
Salisbury
Wilts
The Pie Shop<br />
25 High Street<br />
Salisbury<br />
Wilts<br />
<br />
I used to have ginger hair, then I went<br />
grey and then I became hairless. With ginger<br />
hair, they used to call me "bushy". With grey,<br />
they thought I was a whizz or wizard, and now<br />
I'm called Coot.<br />
and if I display it part of an HTML stream, it looks like this:
The Pie Shop 25 High Street Salisbury Wilts The Pie Shop
25 High Street
Salisbury
Wilts
I used to have ginger hair, then I went
grey and then I became hairless. With ginger
hair, they used to call me "bushy". With grey,
they thought I was a whizz or wizzard, and now
I'm called Coot.
See also ... offsite link - a further description of the HTML and CSS options, and our PHP Techniques course and resources
Posted by gje at 06:40 AM | Comments (0)
Related topics: via article database
Useful link: PHP training
October 10, 2008
Caen Hill and Olivers Castle
It's October - but yesterday was a lovely evening and after the course finished for the day, Mark (one of our delegates) and I went out and spent a brief period looking at some of the local countryside. This is canal side at Caen Hill - about five miles from us.
A handful of miles further on, on the edge of the Downs, is Oliver's Castle - named after Oliver Cromwell, who fought here in the battle of Roundway in the English Civil War. There are boards on the site telling you all about it, and it's a nature reserve too where you can see the local flora and fauna.
The days are drawing in, and there's not much time to take photos before dusk at this time of year - soon, we were onto sunset shots - here with the gaunt trees of Oliver's Castle
And a final shot as a heron comes in to land for the night at Caen Hill.
Posted by gje at 07:55 AM | Comments (0)
Related topics: via article database
Dont bother to write a Perl program
I can - very easily - write a Perl program to process every line of an incoming data file - indeed, that's much of where Perl originated as the "Practical Extraction and Reporting Language"
Here's a short example that processes every line of a file and reports each line that includes the string PHP as the second field of our line (which in the example happens to be a person's top skill):
open (FH,"../../requests.xyz") or die;
while ($line = <FH>) {
chop ($line);
@F = split (/\s+/,$line) ;
if ($F[1] eq "PHP") {
print $line;
print "\n";
}
}
Quick and easy, for sure ... but not as short (nor as quick and easy) as it might be for someone who's written a lot of Perl - this one line does the same:
perl -pae '$F[1] eq "PHP" or $_ = ""' ../../requests.xyz
Perhaps this is so short as to be obscure? If you're working in an environment when you often have to filter out a file quickly, then it's an excellent approach. If you're doing a lot of shell scripting, then a few Perl one-liners like this can save you an awful lot of more complex looking awks and seds.
As Damien Conway (one of the Perl team) said when I heard him lecture: "We're giving you a lot of very powerful tools. Be careful how you use them".
Posted by gje at 05:53 AM | Comments (0)
Related topics: via article database
Useful link: Perl training
October 09, 2008
Perl - map to process every member of a list (array)
Perl's map function (like array_walk in PHP) allows you to do something to every member of a list - thus it often saves you the need to write a loop into your Perl, saves the Perl runtime going back time and again to the interbal byte code generated by the compiler, and can be very efficient.
There aren't a large number of map examples in the training course notes that I use; in Perl there are many ways of doing anything and there are always alternatives but - as appropriate - I do add extra demonstrations in as I present the material. Here - four days into a five day course - are my examples of map so far this week:
@vals = map($_*5,@vals);
Take all the members of a list called @vals, multiply each of them by 5, are return them to a list of the same name (@vals), overwriting the original
$plist = join(", ",map (ucfirst lc, @peeps));
Take each element of the list in @peeps (probably people's names) and convert them all to lower case, then capitalise the first letter of their first name. Join the resulting names together with a space between each of them, and put the resulting single scalar string that results into a variable called $plist
map(printf("%20s %d\n",$_,$counter{$_}),@hio[0..9]);
Take the first ten elements of a list called @hio which in this example contained a sorted list of host computer names) and print out, formatted, the corresponding members of the hash called %counter - which contained elements keyed to those host names, with values which were the number of times that the particular host had accessed our server.
This last example is notable in that it makes no use of (throws away) the list returned by map - which will just be a list of "1" values indicating success - the important result is the effect of the 10 operations of printf
Posted by gje at 11:38 PM | Comments (0)
Related topics: via article database
Useful link: Perl training
October 08, 2008
What a shock
You have probably seen the last pictures on this site ... taken with the digital camera I have been using for a couple of years. It was water resistant, contents-of-pocket resistant, and said to be shock resistant - but it turned out not be shock resistant enough for me - a clumsy oaf who managed to shut it into my Lisa's car door in Chippenham on Saturday evening. It now has a screen where I can see the left of the picture I'm taking but not the right, and where I have to guess at some of the menus. That I managed to do this half acceptably is shown by the pictures of Bathampton and Claverton Pump that have appeared here in the last few days.
"Get it fixed" is my first thought. Where other people have a mobile phone that becomes a very part of them, so was that camera to me. I have to watch how strongly I word the bond, as Lisa could end up thinking I have fonder words for the camera thaN I do for her (Lisa - if you're reading this - it is said tongue in cheek!). But the cost of fixing it would have been almost as much as (or perhaps more than) the new camera cost, and perhaps technology had moved on. Deep breath, I hadn't intended to get a new camera ... but it's new camera time!
So I'm back to learning a new camera now ... and you'll have to forgive me while I practise and post up a few trial and test photos ... here are some taken in the early days of this week.
The Town Hall at Melksham, with autumn flowers on the roundabout
This is the road works season in Melksham, and Bank Street is close once again!
Well House Manor early this morning, with bright sunlight on the front of the building.
Here's an interbal picture - our bedroom 3.
And here's my first picture with the new camera of delegates on a course.
I must admit that the new camera is a (10 Mpixel) development from the old one, so that although there are some things I need to get used to / learn into, it's much the same and I should be up and running again quite quickly.
Posted by gje at 04:12 PM | Comments (0)
Related topics: via article database
Perl - Subs, Chop v Chomp, => v ,
During courses, I end up writing a lot of short demonstrations to show particular features of a language - this week, it's a Perl Programming Course so those examples are in Perl.
Some interesting Perl facts ...
a) The => operator can be used to replace the , ("the equals, greater than can be used to replace the comma")
b) chop and chomp have the same effect on a line of text just read in from STDIN (which usually means "read from the keyboard")
c) It's a good idea to take commonly repeated pieces of code and save them in a block - called a sub or subroutine in Perl - so that you don't have to keep repeating yourself AND so that you can present your user with a consistent interface
The programs I come up with are odd / quirky / memorable and if you look back at them later will leave the new reader scratching his or her head - but the key word is memorable. Here's the program that went some of the way to explaining the key perl facts above:
sub getui {
print "$_[0] - ";
chomp ($rv = <STDIN>);
return $rv;
}
print "How kids yagot? ";
chomp($nk = <STDIN>);
print "And how many goldfish? ";
chop($ng = <STDIN>);
$nz = getui("how many zebras?");
print "Actimel $nk pounds\n";
print "Cream Cheese ",$nk," kiddoes\n";
print "Milk $nk pounds\n";
print "Yoghurt "=>$ng=>" goldfish\n";
print "Bananas ",$nz," zebras\n";
Learning in this way is not only useful, but fun! If you're looking for the dates of the next public Perl course ... as I write (early October 2008) the next course starts on 27th October, and if you're reading this later on the archive and have missed that start date, you can find what's coming up here in our index of courses. I look forward to helping many more people (such as yourself, perhaps?) enjoy learning Perl!
Sample Output:
Dorothy:p1 grahamellis$ perl tootoo
How kids yagot? 3
And how many goldfish? 7
how many zebras? - 4
Actimel 3 pounds
Cream Cheese 3 kiddoes
Milk 3 pounds
Yoghurt 7 goldfish
Bananas 4 zebras
Posted by gje at 08:10 AM | Comments (0)
Related topics: via article database
Useful link: Perl training
Question Mark - Colon operator (Perl and PHP)
The ? and : operator in Perl and PHP allows you to write a single statement that's both an if and an else without the need for all the clutter of keywords, extra variables, and so on if all you want to do is come up with two alternative words.
Here's an example in PHP - throwing a number on a die, and telling the user to proceed if the value thrown is a five or six, but to try again is it's a 1, 2, 3 or 4:
<?php
# Throw a die
$throw = rand(1,6);
print ("You threw a $throw which means you should ".
(($throw > 4) ? "proceed" : "try again").
" at the next turn\n");
?>
Here's how it works ("all our code is tested" as I wrote in an email to someone yesterday!)
Dorothy:p1 grahamellis$ php pz
You threw a 3 which means you should try again at the next turn
Dorothy:p1 grahamellis$ php pz
You threw a 6 which means you should proceed at the next turn
Dorothy:p1 grahamellis$
Here is the same functionallity using if and else:
<?php
# Throw a die
$throw = rand(1,6);
if ($throw > 4) {
$action = "proceed";
} else {
$action = "try again";
}
print ("You threw a $throw which means you should ".
"$action at the next turn\n");
?>
In Perl (I'm running a Learning to Program in Perl course this week, which is where this article originated!), you have the same thing - and a wide variety of other convenient alternatives to if for conditionals and while for loops. I've posted up an example that uses until and also the ? : pairing at http://www.wellho.net/resources/ex.php4?item=p206/golf ... in this demonstration, you enter the number of individuals or teams you have signed up for a knock out competition, and the program tells you what your target should be if you want a perfect knockout with no need for any "byes" in the first round. Here it is running:
Dorothy:p1 grahamellis$ perl golf
How many people? 6
You really need 8
Dorothy:p1 grahamellis$ perl golf
How many people? 8
You're fine as you are with 8
Dorothy:p1 grahamellis$ perl golf
How many people? 11
You really need 16
Dorothy:p1 grahamellis$
You'll note - once again - the subtle use of ? : in the code to change the text "you'll really need ..." into "you're fine as you are with ..." - oh the power of Perl and its plethora of operators.
Posted by gje at 07:21 AM | Comments (0)
Related topics: via article database
Useful links: Perl training, PHP training
October 07, 2008
Which is your best hotel room?
"Which Room would you recommend for a special weekend ..." Question on the phone from customer booking at Well House Manor. And Lisa's comment - "I feel awkward giving my personal opinion - it may differ from what the customer's would be." Well - give them the data and let the customer choose!
"We have a lot of customers who ask for the same room they were in last time when they book - and that's for every room in the hotel. Every room has its fans"
• Room 1 is a quiet room at the back of the hotel, double, with a large circular-doored shower with a seat in it. [see bedroom 1]
• Room 2 is larger that room 1 (mind you - room 1 is not small) again at the rear of the building, overlooking the main garden and the apple trees. Usually a double, we'll convert room 2 into a twin if required. [see bedroom 2]
• Room 3 has a large sleigh bed and a double ended bath (no shower) in a light and airy bathroom. It overlooks the main lawn and is situated closed to the main stairs. [see bedroom 3]
• Room 4 is the largest in the hotel - configured as either a double or twin room (please let us know when you book) and with a large walk in double shower. Again, this room overlooks the lawn. [see bedroom 4]
• and Room 5 is at the front of the hotel, with a King double bed, and both bath and shower. There's a fireplace in the room (regrettably not working) and the desk is situated in the bay window so that you can look out while you work. [see bedroom 5]
Which would I sleep in? Any of them ;-) ... and indeed I HAVE tried out some of them so that I'm fully aware of our product from a user's perspective, and we continue to encourage staff to stay and report back occasionally.
Posted by gje at 06:07 PM | Comments (0)
Related topics: via article database
FSB - an update.
Last Tuesday, I got a phone call at lunch time asking me if I could attend - as a witness - a D&D (Dispute and Disciplinary) hearing of the FSB (Federation of Small Businesses) at Bath that afternoon. Unsurprisingly, I was giving a training course and couldn't oblige, but the D&D committee went out of their way to receive my input starting at 9 p.m. that evening, and lasting for over an hour.
Why me in particular? Well it wasn't me in particular - the hearing into allegations made by an employee of the FSB against the chair of our branch which had led to her being suspended from office for well over a year lasted for most of the week. I didn't comment earlier as it was "sub judice" (I think that's the term), but I am now happily able to report the verdict that cleared both our chair and her husband of the matters for which they were suspended for in late spring / early summer of last year.
The Committee's decision is a "narrow" one in that whilst it clears Marion and Malcolm, that's as far as the committee can go. As I understand it, it is beyond their remit to actually lift the suspension. Now you would think in the interests of common justice that such a lifting would happen immediately, with full recompense and re-instatement of Marion and Malcolm, wouldn't you. We'll have to wait and see on that one. With just the occasional exception, I've learned as I've watched this matter from the sidelines that the FSB is much more a member-led organisation in word than in deed.
If you would like to read back to my previous articles on this subject:
26th May 2008 - The old sayings are the best (FSB)
18th February 2008 - FSB, EGM, AGM.
19th January 2008 - Summer Ball at Bowood - Saturday 12th July 2008
20th December 2007 - FSB leaves its members feeling like mushrooms
13th September 2007 - FSB (Federation of Small Businesses) Western Region
27th June 2007 - Is this how to run a business for businesses?
And this is what the FSB should be about in my view - a business networking event on 20th April 2007 (yes, 18 months ago) where we had an opportunity to meet 19 other local businesses for our mutual benefit.
Another view of what the FSB should be doing. The Wilshire Business of the Year awards, 13th December 2006, in Swindon where we were finalists and teh FSB sponsored one of the sections
Here's hoping that the FSB can get its eye back on the ball soon ... that we can soon benefit again from our membership as we were doing in the Spring of last year, being piloted by a committee in North and West Wilts that we have elected from amongst all of our members, without exclusions, diversions or suspensions preventing it.
Update - November 2009. This article has recently been brought to my attention as being potentially biased, incomplete or in error. I am happy to make necessary additions to complete the story or reflect other views, and to correct any error of fact. See here
Posted by gje at 08:06 AM | Comments (0)
Related topics: via article database
October 06, 2008
Claverton Pump
What's inside this little building that sits over a back water of the River Avon just a few miles up river from Bath?
A 25 foot wide water wheel, with each scoop on the wheel taking no less than half a ton of water [background], and a set of full functioning gears and flywheel - the whole being fully operational!
The fly wheel drives two huge beams, which in turn operate pumps that use to raise water up to the Kennet and Avon Canal that runs along the hillside above. Read more about it at the official site here.
The River Avon rises and falls quite dramatically at times of heavy rain, and indeed it was rising late yesterday when we dropped in by chance at the pumps.
Although shut(ting) down for the day, one of the team of volunteers briefly showed us around and I was able to take these pictures, including this one where he indicated where the two floods that have already had this summer rose to. Astonishingly, apart from moving some of the more delicate exhibits up above the water level, they can just let it flood - the engineering is so robust that it's not a major concern or panic - indeed, he also showed us the mud lines on the gears and flywheel which clearly indicated the angle they happened to have stopped at before the floods.
And a big THANK you to the gent - who's name I don't know - for letting us have that brief look around; it's little gestures like this, at the end of his day, which really "made" it for us.
Posted by gje at 07:24 AM | Comments (0)
Related topics: via article database
October 05, 2008
Autumn
We're into Autumn, and on a blustery Sunday we went out to show Chris's mother in law, visiting from South Africa, some of the local scenes in Wiltshire, and Bath and North East Somerset (BaNES).
The hardier souls were out in the countryside - a handful of boats moving on the canal, fishermen, cyclists ... and of course the dog walkers, who will still be out walking their dogs long after the canals are beset with winter stoppages and the bicycles are in the back of the garages.
The Cafe at Avoncliff remains open from 10:30 a.m. until 6 p.m. until the clocks go back ... and of course the pubs continue to be open for extended hours as illustrated at Bathampton.
"Where's my master" asks one lonely, 4 legged soul left out in the cold!
Posted by gje at 11:41 PM | Comments (0)
Related topics: via article database
October 04, 2008
Sorting objects in PHP
The OO model in PHP is very powerful indeed - and much more code is now written using the facilities it offers than was the case a year or two ago. On yesterday's Object Oriented Programming in PHP course, I wrote a new example that nicely brought together many of the facilities on offer - you can see the full sample code here.
One very common requirement is to sort an array of objects in PHP, and if you just use the regular sort function, you'll end up sorting (I think) based on the memory address at which they are held. That is never what you want! Instead - you should use usort
Here's my example of a call to usort:
usort($wellhousemanor,array("transact","mvf"));
And that sorts an array of objects in the $wellhousemanor array, using the static member function called mvf in the class transact to compare pairs of records. All you (as the application programmer) need do is make the call in this (rather curious, it must be said) way. If you're the programmer writing the class, you simply provide a method of the given name that takes two parameters and return negative if the first object passed should come earlier, positive if the second object passed should come earlier, and zero to indicate that the objects are equally ranked for sorting.
Here's my example comparator:
static function mvf($first,$second) {
if ($first->getvalue() > $second->getvalue()) return 1;
if ($first->getvalue() < $second->getvalue()) return -1;
return 0;
}
Q: I'm a PHP programmer - should I use objects these days?
A: In most cases YES - exceptions are minimum maintainance jobs on older code, and tiny applications where you'll never have more than a few lines of PHP. And even if you're not writing your own objects, chances are that you'll use objects that other people have written and perhaps contributed via something like PEAR.
Posted by gje at 05:47 AM | Comments (0)
Related topics: via article database
Useful link: PHP training
October 03, 2008
Calling base class constructors
In all object oriented languages, you have a facility called inheritance where you can define one type of thing ("class of object") based on another, and the newly defined class ("subclass" or "extended class") takes the initial ("base") class as it starting point.
In your code for your base class, you'll have some logic which sets up new objects (a "constructor" method), and you'll have code in your extended classes through which you set up objects of that extended type. Almost inevitably, your extended objects will be pretty similar to your basic objects but they'll have a few extras, and so the writers of Object Oriented languages provide you with a way of calling the base class constructor within (or before) your extended class constructor. The base class is sometimes called the parent class. Let me translate that into an example in plainer English.
"A Train journey is a specialised type of public transport journey. If you're setting up a train journey, you'll want to set up a regular public transport journey within it first, with attributes like where it goes from and to, and at what time and who runs it. Then you will add some train extras such as how many carriages long it is"
How does this work in C++?
Train::Train(int nvh, int vhc, int xtrwa ) : PubT(nvh, vhc) {
tronly = xtrwa;
}
A Train is a PubT. When you create a train (with three parameters), you create first a PubT passing the first two parameters in to it, and them you perform the extra actions in the code block - which is saving the third parameter.
Course - C++ Programming
How does this work in Java?
public Train (int nvh, int vhc, int xtrwa) {
super (nvh,vhc);
this.tronly = xtrwa;
}
How does this work in Python?
def __init__(self,nvh,vhc,xtrwa):
pubt.__init__(self,nvh,vhc)
self.tronly = xtrwa
Course - Python Programming
This is old style classes; in new style classes, you'll call parent on the current class to avoid having to state the name of the parent class within the extended class definition.
How does this work in Perl?
In Perl, you "roll you own" ... it's so flexible and there are so many options it's almost untrue! Here's an example:
sub new {
my ($self,$nvh,$vhc,$xtrwa) = @_;
my $cc = new pubt($nvh,$vhc);
$cc->{"tronly"} = $xtrwa;
bless \%{$cc};
}
Course - Perl for Larger Projects
How does this work in [incr-Tcl]?
constructor {nvh vhc xtrwa} {
pubt::constructor $nvh $vhc } {
set tronly $xtrwa
}
}
Course - Tcl Basics and please let us know when you book that you would like us to add in strong coverage of Incr-Tcl
How does this work in PHP?
public function __construct($nvh, $vhc, $xtrwa) {
parent::__construct($nvh, $vhc);
$this->tronly = $xtrwa;
}
This example is for PHP 5. If you're still using PHP version 4, you'll call your constructor the same name as the name of the class, and call the base class constructor via the class name.
Course - Object Oriented PHP
def initialize(nvh, vhc, xtrwa)
super(nvh, vhc)
@tronly = xtrwa
end
How does this work in Lua?
Lua is a small language which provides you with facilities through which you can write OO like code but it is not strictly objects. You can set the metatable of a table [object] to the metatable of the table which you wish to be the parent, then modify it - thus emulating the facility that I'm talking about in this article.
Course - Lua Programming
Posted by gje at 07:13 AM | Comments (0)
Related topics: via article database
October 01, 2008
Icelandic Badge
Lisa's doing new staff badges for us all - both ID badges and swipe cards - and they're personalised.
We have our own picture on our ID cards so that customers can recognise us, and they're to a fixed Well House Manor format. But we have a choice with swipe cards of - more or less - anthing. And I have chose one of my own pictures, which you see accompanying this article.
Everyone has been giving a great deal of thought to the picture they would like, as they're pictures we're going to use / live with for years and there's all sorts of possible significances. Perhaps I should have chosen a picture of Lisa - I would have done so, save for the fact that people might think it was her card! But anyway I have very fond memories of a holiday in Iceland. And a picture that I took which still says "wow" to me. So I have chosen that. You can click on the image to see it larger if you like. And you can see more of my Iceland pictures via here
Posted by gje at 11:38 PM | Comments (0)
Related topics: via article database
