Main Content

Breaking bread

Archive - Originally posted on "The Horse's Mouth" - 2006-06-22 07:17:45 - Graham Ellis

How can I take ONE thing, discard some of it, and end up with MANY things all of the same type as the original? Surely that doesn't make sense does it?

I could take a packet of half a dozen rolls from the supermarket, made (as they often are in the UK) as a single piece of bread with narrow "tear" points, and tear into six pieces. A few crumbs to be thrown away - and there you have it. Six things (of type "piece of bread") where the sum total is actually LESS that the one thing ("piece of bread") that I started with.

This action of breaking bread has a parallel in programming. In Perl (split), Python (split) and PHP (explode, split) amongst others, you can take a single string and break it down into a whole list (Perl, Python) / array (PHP) of smaller strings. You'll often want to do this if you have a string that's a line of data read from a file, and you want to break it down into a series of strings each of which is an individual field.

@pieces = split(/\s+/,$line); # Perl