Perl;
print { open my $out, ">", "pidfile"; $out or die } $$, "\n";
Ruby;
File.open('pidfile', 'w+'){ |fh| fh.puts Process.pid }
I could have used ‘$$’ instead of Process.pid, but I prefer readability
PHP;
file_put_contents( 'pidfile', getmypid() );
Yeah I know, I know but anyway…
Related posts:
- Introducing php-tracer-weaver php-tracer-weaver is a tool for automatically generating docblock comments, with...
- Ready for PHP & MySQL Week at SitePoint? To celebrate the release of the new edition of well-loved...
- Is Ruby’s Popularity Fading? Ruby has enjoyed a ton of hype over the last...
- Interactive CLI password prompt in PHP Just a quick tip, since I spent a good hour...
- How to Use PHP Namespaces, Part 3: Keywords and Autoloading In the final part of his series explaining PHP namespaces,...







file_put_contents (and also file_get_contents) are absolute live savers. As long as the files to write or read aren’t too large, they’re great functions. And I find the PHP version of the above scripts to be the most… easily readable. Then again, I’ve not done much work in Perl or Ruby, so I’m probably a little biased!
May 27th, 2006 at 8:40 am
Just to defend the other languages, you can easily create a method/function that does the same thing as PHP’s file_put_contents(). But you are right, it is not built in.
Not to start a flame war, but I find Ruby’s way of doing things much nicer (most aspects, at least). However, for hardcore C-esque type programmers, Ruby’s syntax is a bit irregular. I have never used Perl, though, but I have heard it is similiar to PHP.
May 27th, 2006 at 9:50 am
I agree. I do find myself wishing for PHP’s file_put_contents method while in other languages.
But, just to have a little fun with Ruby:
May 27th, 2006 at 10:01 am
PHP’s huge library of built-in functions is definitely a strong point for the language.
May 27th, 2006 at 10:15 am
And the fact that they’re all in one flat global namespace is definitely a weak point for the language. ;)
May 27th, 2006 at 11:35 am
Not really. Most of them (there are a few exceptions, unfortunately) are properly prefixed and don’t conflict with anything in user space anyway. The only majorly annoying naming clashes come from the SPL (which is too damned useful to ignore and yet uses up a lot of the really good names).
I’m not saying PHP doesn’t need namespaces (it does), but for most things there isn’t a huge tangible difference.
Namespaces only have three real advantages anyway:
1. You get shorter, cleaner function names WITHIN the namespace.
2. You get shorter, cleaner function names when using the namespace and there aren’t any conflicts (using mysql::query instead of mysql.query or mysql_query makes no real difference).
3. (if the language supports it, few do), you can import the namespace as an alias — something like “use namespace foo as bar; bar::stuff().
Anyway, that’s off topic.
PHP is great because it just makes sense. No stupid, hard to remember, obtuse operators (perl is the poster boy for this, but ruby has a lot of annoying ones as well), clean syntax that closely resembles the other languages that you work with on a regular basis (C, Java, Javascript, CSS to a certain extent). file_put_contents is just a good example, but in truth you see this all throughout php.
May 27th, 2006 at 12:05 pm
File.open('pidfile.txt', 'w+').write(Process.pid)or:
def file_put_contents(file, contents) File.open(file, 'w+').write(contents) endOr more rubyish:
def File.write(file, contents) File.open(file, 'w+').write(contents) endBut the first is good enough for me.
May 27th, 2006 at 6:05 pm
Also, I love how easy PHP is to install! I got really frustrated with perl and mod_perl.
May 27th, 2006 at 6:06 pm
Namespaces are just objects in Ruby, you can easily alias them.
May 27th, 2006 at 6:11 pm
For just straight function calls, you can do that in any language. It’s only really interesting when objects are involved.
May 27th, 2006 at 9:00 pm
This is a worst pro-PHP reason I’ve ever seen. One could write a followup “Reason to like Ruby” and compare foreach loops from other languages vs. iterators. And this could go on and on for every language…
Want
file_put_contentsin your language? Write it. You won’t notice the speed difference as opposed to built-ins because it’s a one liner in almost any interpreted language.May 27th, 2006 at 11:17 pm
My reason to hate PHP:
can not pass functions as arguments …
May 28th, 2006 at 2:40 am
Another reason to hate PHP: (just recalled from memory)
array syntax
vs
personally, I think array is the most powerful thing in PHP. but it has a really stupid syntax. array(array(array(…))) :(
May 28th, 2006 at 2:42 am
You say foreach and iterators like they are two different things. PHP does support both and quite well with SPL (another reason to love PHP/SPL). However, there isn’t any optimization that can be done with PHP iterators other than caching the output.
I have only tested iterators in Java, Perl, C++, and PHP. It would be unfair to compare Java, C++ iterators to PHP. I did compare Perl iteration against Java and Java won (however, it was only to prove my teacher wrong about the slowness of Java, but the tests were accurate).
It would be interesting to see iteration timed tests with PHP, Ruby, and Python and see how they stack up against one another.
May 28th, 2006 at 2:51 am
this is personal preference and has nothing to do with readabilty or ease of coding. harry demonestrated that what other languages do in kinda long unfriendly was was achieved with 1 easy line with PHP and I am sure that Harry isn’t implying that PHP is flawless, right Harry? ;)
May 28th, 2006 at 5:52 am
Another reason: it forces you to write ;;;; all the time. Another: explicit return is required. Another: classes are not first-class (;-)). Another: there are many anti-sql-injection/escape-functions, but which works/is safe? Another: strange naming: str_replace or strreplace? strlen or str_len? Etc. etc…
May 28th, 2006 at 6:20 am
Speed doesn’t matter much? The syntax/semantics does/do:
or:
I prefer the first.
May 28th, 2006 at 6:25 am
Some random provokers;
Etnu already been over this but another angle on why this is less significant (compared to other issues PHP has) – by way of dubious analogy – consider Wikipedia: they’re using a single namespace for all documents and have considerably more documents than PHP has functions. The point being, managing all those functions or conflicts with user defined functions are not really problems PHP has. It just isn’t pretty (and suffers from what Etnu described).
I say this because this problem gets quoted often is a major PHP problem. For me far more significant is situations where script X.php will run under one server but not on a different server running the same PHP version. If you’re writing code to distribute, the list of potential “gotchas” is many. For example, off the top of my head, consider addslashes() – note this one sentence;
Say no more.
Well … you can but I guess you mean closures, which PHP doesn’t really do. There’s create_function but this is really eval() by another name. You can pass a function name in a variable then call it like a function e.g.;
In practice you need to use objects, which you can pass around.
Agreed.
Where I think this is interesting is as illustrative of how PHP evolves and how these functions came to be part of the core distribution.
More in depth than you want but check this out: http://shootout.alioth.debian.org/gp4/index.php – of the dynamic languages, Python comes out looking good all round.
Yeah but that arguing leads to Python, where you can also skip curly brackets.
You mean PHP doesn’t have implicit returns? PHP functions don’t have to have a return statement, but if they don’t, they implicitly return NULL, not the value of the last executed statement. Personally not entirely convinced of the merit of implicit returns, having run into them in Perl. If you want to reinvent LISP OK, but otherwise think it’s bordering on obsession with syntactic glory.
That’s a good point. And neither are functions. Shame in both cases although I can imagine potential performance problems if they get tacked on to PHP later – have class as “concrete” helps keep a bunch of evaluation to “compile-time”, when the script is parsed (making the OPCODE cache actually useful). Doing this well is probably a massive effort.
See the start of this comment ;)
Yeah but I don’t regard that as a real issue. Once you know, you know and failing that, an editor with auto-complete will help.
That simplifies via array_map() e.g. (create_function but with less code);
Safer is this;
May 28th, 2006 at 10:03 am
I guess it depends on what your personal situation is. You complain of the difficulty in writing PHP that has to be distributed to servers running different PHP versions, or running different configurations. If you are the type that writes code that has to be distributed that way, I can see why the lack of namespaces would be just a minor irritant comparatively. However, for quite a lot of us in “the enterprise” (sorry to bring that term into the discussion) we are in complete control of the version of PHP and the configuration on all the servers we are concerned with deploying on, so other issues (like the no-namespaces issue) becomes more of a thorn in the side.
What makes a good system for naming Wiki documents and what makes a good system for referring to global symbols within program code are not the same. Namespacing is all about avoiding name collisions when you have a set of names that may (usually will) have to be combined with an as-yet-unknown other set of names. Is this an issue that Wikipedia has to deal with on a regular basis? Do they often merge their huge database of wiki pages with other wikis? I think not. A new article has to be created, so someone creates it, and if they’ve chosen a name that is already in use then they simply choose another. No big deal.
Program code is different. Naming collisions are a very real problem once you have to combine a non-trivial amount of code with another non-trivial amount of code. If you have a collision you get to choose one of the colliding symbols and give it a new name, which forces you to update all references to it. If you only have a few files and a few hundred lines of code, this is no big deal. If you have code numbering in the tens of thousands of lines, it becomes more irritating. Especially when working in a language that lacks automatic refactoring tools. (Yes, I know about grep, awk, sed, etc. …) And if the code you are integrating doesn’t exist in a vacuum (i.e. other projects depend on it) then this irritation can increase exponentially.
Back to your Wiki analogy… Let’s suppose that large wiki’s did frequently merge with each other. Imagine the case where a wiki page in one system has hundreds of references to it sprinkled throughout, and the same-named page in the other system similarly has hundreds of references to it, and they now have to be integrated? If this was a common need then I suspect wiki’s would develop a namespacing system very quickly.
Of course, namespace collisions can be avoided in PHP by giving all of your class names Long_And_Cumbersome_Prefixes, but that just trades one irritation for another. Now you have excessively long identifiers all over the place, which is an impediment to both reading and writing the code.
I’ll admit that the lack of namespaces for functions isn’t really much of a practical problem, although it may make it more difficult for some newcomers to intuit the name or location of a desired function (for example, in Java if you need to know how to lowercase a string, you can guess that it’s probably a method of the String object), and it most certainly offends aesthetically. However, the lack of namespaces for classes is a very real problem that many people have with PHP and this is why it is so often quoted. If I never see another class named something like “PHPUnit2_Extensions_MockObject_Builder_InvocationMocker” it will be too soon.
May 28th, 2006 at 11:25 am
File.WriteAllText( “pidfile”, getmypid() );
May 29th, 2006 at 10:49 am
file_get_contents is still overlooked, just consider what file_get_contents can do..
* Read over File System
* Read over web
* Read over SSL
* Unzip gziped streams directly..
and probably more..
May 29th, 2006 at 2:31 pm
Agreed, that is cool.
May 29th, 2006 at 4:46 pm
Or, you use ASP.NET and write your own functions and create you own objects in an ordered managed environment.
May 29th, 2006 at 11:40 pm
I would really, really like to see namespaces, but I would rather it function more like D or Java and not where you explicitly assign the namespace, but I think both explicit and implicit namespace support would be good.
However, I don’t want PHP to become Java (or do I? Hmm, perhaps not). I do prefer objects over functions, which is why I was interested in Python, but I’m not about to join a cult just to program a language.
May 30th, 2006 at 12:34 am
You don’t have closures, but you most certainly can pass functions as arguments.
Not having closures is annoying, but, well, most programmers don’t really understand closures anyway. As much as I love functional languages, getting other people to really understand them is difficult unless you’re lucky enough to only work with really intelligent people.
May 30th, 2006 at 2:24 pm
You should check out C#’s equivalent… you have to open a streamreader, close it… around 3-4 lines
But hey! Just condense it into a function and keep it in the toolbox ;)
May 30th, 2006 at 8:17 pm
I think a lot of people are missing the point of this. I believe what Harry is trying to point out is that most of the functionality programmers need is well named and works as you expect.
file_put_contents( 'pidfile', getmypid() );It’s simple, it works how you expect and it’s built in. You can easily recreate this in any language by writing your own function, but the point is it’s already there and ready in PHP. This is the main reason I still use PHP for the majority of my personal projects even though I’m primarily a .NET developer at work.
Remember what PHP was made for, it wasn’t intended to be a supercharged, enterprise development tool. It was designed to be an easily approachable server-side language, and one-liners like this are a perfect example of how PHP has maintained that ease-of-use even though it has grown well beyond initial expectations.
May 30th, 2006 at 11:30 pm
I don’t think that could have been said much better, LunchBox.
May 31st, 2006 at 1:18 am
you can actually go back from .NET to PHP and feel good? :)
May 31st, 2006 at 1:26 am
Yes I do mean closures. I like Scheme :) Variable functions and call_user_func() are cumbersome.
Anyway, one possible workaround:
And the array() syntax
Yes I admit it’s just personal preference, but when you realize PHP’s array is so powerful and you use it intensively in your code, you might also be sad to write array(array(array(…))), like I do :P
May 31st, 2006 at 3:15 pm
I don’t know why the code doesn’t show up in the last post. Paste it again here:
Hope it works :(
May 31st, 2006 at 3:19 pm
Agree, and especially when you simulate namespaces using objects, like:
Yet it’s a shame there’s not way to simulate namespaces for objects. :(
May 31st, 2006 at 3:26 pm
I think SitePoint should improve the code block … it sucks :(
May 31st, 2006 at 6:30 pm
I could argue that once you know that
xyz_abc_dfsbfgjdsfbgvfhgsdfmeanssquare root, you know and never need to think about it. And the language is independent of an editor, so that argument doesn’t hold (unless the language is, say Smalltalk with Squeak, but it’s still essentially independent of the implementation). Consistency means I can focus on the real things, and need not stop to think twice about a choice the language inventor may or may not have made.PHP doesn’t make sense. Is it fileputcontents or file_put_contents or file_putcontents? The syntax isn’t particularly “clean” either. It does resemble C etc., but it’s not very “clean”. That’s a hard concept to define, but let’s just say it means easy to read and easy to write. You need some concistency to achieve that. PHP misses that.
Dumb languages make for dumb users. The best languages are those that aren’t dumb. If you don’t understand closures, you can still use them if they scale down (they certainly do in Ruby). Your example is just a shortcut for eval. It’s not passing a function, it’s syntax sugar for evaluating a string. Even C has function pointers.
June 1st, 2006 at 5:47 am
Point taken, zjcboy. I fixed your code (I think).
It’s actually works ok, but we haven’t made it very easy to use — I’ll look at that. There’s a syntax guide at the bottom of the right column.
You can use
<code>to markup inline code in your comments.Use
<pre>tags to wrap<code>for code blocks. Optionally add a class to the<code>to get syntax coloring.June 1st, 2006 at 10:40 am
AlexW,
Thank you for fixing my code. :)
Sorry I didn’t notice the syntax guide – the page is too long and the guide is far from the text field.
Isn’t it a good idea to place the syntax guide directly below the text field? Just for convenience :P
June 2nd, 2006 at 3:55 pm
Ruturaj K. Vartak Says:
It can read anything you imagine. Just write a stream wrapper, register it with a name (say, mywrapper) and you can happily
file_get_contents('mywrapper://...')for the rest of your life.TheLunchBox Says:
Yeah, you are returning to the most used pro-PHP quote: “It just works”. PHP is robust, fast, it works; all of the functions you need are already there. It’s stable and easy to deploy; it is well-known and established among (web) programmers.
But to me there is more to a good language than “it just works”. There are naming standards, syntactic sugar, language constructs, code beauty. PHP5 is making code beautiful again by putting things into classes, by providing common database access (PDO), by use of magic methods in objects and exceptions, and so on. But where is your PHP5 adoption? Large majority doesn’t use it – PHP4 “just works” for everybody. “Just works” being spaghetti code, no separation or reusability, hard maintainance,
mysql_queryand bunches of globals or constants sprinkled everywhere… and so on.PHP spoiled people – it’s time to get them in shape. It will be a hard process… I just hope Zend Framework or ezComponents save PHP.
June 4th, 2006 at 4:33 am
I agree that you don’t understand them the first time you see them, but they were easy to understand for me. Understanding for loops was much harder… (note that I’m not saying that for loops are harder than closures, but it is normal to learn for loops before closures (unless you’re starting with Scheme/Haskell/etc), and in that stage for loops are hard to understand).
Closures are like OOP objects, but different. An object = Data + code = instance variables with methods, A closure = Code + data = a function + variables in scope.
June 4th, 2006 at 6:40 am
I don’t know people are arguing over closures. In PHP 5 you can have use the Factory class model, which I think is the same thing and much better.
Doing some JavaScript over the past week has left me feeling happy about JavaScript function closures. However, while it is easy to understand, I don’t see it as any different from the Factory model, just different name.
What is annoying however in JavaScript is the this scope forcing you to use function closures. I think PHP is great that you don’t NEED closures, I can create closures in PHP and call it a hack all you want, but a closure is a closure no matter the syntax.
Writing a function inside a function I think leads to bad code. Write a class and just make the function private and return it. Be done with it.
What PHP 5 did that is also great is Reflection and I don’t know Ruby or Python to know if they also have this feature. What is nice about it is that it is easy (if however limited it is at this point) and straightforward. Look at it to see how PHP is moving forward and behold the power of PHP 5.
I do recall an article or blog post saying that it is pointless to compare languages as being better than the other. This is true. Your choice of Programming language is your own and saying it is better because of this and this feature to convice someone else isn’t going to work because they would have another feature that they love about their language.
Another way to look at it, it is like saying English is better than some other language because of its character base.
June 6th, 2006 at 12:06 am
santosj, I don’t know which you refer to, but factory method / abstract factory has nothing to do with closures.
A key point of closures is that they can “capture” variables from the scope where they are defined, but access them when executed later. In a number of situations this enable the programmer to significantly cut down on the code, while more efficiently conveying the intention. Less code = less bugs.
PHP, Ruby, Perl, C#, Basic and assembly language are all turing complete, which means that any program can eventually be written with any language.
But that is not a test of the feasibility of a language in a given problem domain. It does not mean that they are equally well suited for any task. Nor does it mean that they are at the end of the evolution and should not try to learn from eachother.
PHP has some significant problems when compared to more clean, strong conceptual languages like Ruby, C#, Java and even EcmaScript (JavaScript).
Robust programming language design is very hard to do. Sometimes when you put in a feature it does not pan out as expected when released for the general use (abuse) by the sometimes less than stellar developer. Java has got issues with checked exceptions. PHP has problems taming variable interpolation, single namespace, inconsequent(multiple) naming conventions, bad namings, wishy-washy OO support, among other things.
June 6th, 2006 at 4:09 pm
You don’t understand, closures can introduce bugs unless you know what you are doing. Using JavaScript as an example.
A simple way to fix scope issue is this hack.
var _this = this; var func = function() {_this.function()}I see no difference from
function func1() { var func2 = function() { return 'test'; } return func2; }class func1 { public function __construct() { return 'test'; } }That fact that you start classes with the function doesn’t help matters.
An closure in PHP
class Test { public function __construct() { return $this->testString(); } private function testString() { return 'test'; } }Being able to return functions means nothing at all.
These are the result of Poor Programming Practices and not bad programming languages:
Naming Conventions
Bad Namings
“Wishy-Washy OO Support” is just what you tell your friends, but I don’t think anyone else buys it. PHP 5 should fix all of your troubles with PHP OO. However, I do wish it was optimized better, but PHP is not Java.
June 7th, 2006 at 5:25 am
I discovered Php 3 years ago.
My professionnal experience is on huge computer (IBM Mainframe, MVS)
My experience in programming was with Basic, Pascal and Cobol.
For personnal purposes i started HTML about 10 years ago,
Javascript 3 years ago.
I found PHP very easy to install on my PC Win XP (Apache too…).
And had in a week time the ability to develop a new website for a local association.
So has i have no other experience in other web server programming language, PHP IS MY FAVORITE.
Easy to implement
Easy to use.
June 8th, 2006 at 5:40 pm
June 8th, 2006 at 10:04 pm
Programming always requires a learning curve. I’ve seen a fairly well established shopping cart system that was written in Perl that’s used on quite a few sites. However recently having to configure it myself, I found myself wondering where the ease in administering the product is. Especially when the product has it’s own additional language (plus associated syntax) on top of Perl, which is all imbedded within a file with an extension of ‘.html’.
Now mind you the product is being taken away from it’s original intent (shopping cart system), and used for another (auction system).
Personally I often find it easier to create a system from scratch, because having to modify some of the hideous code that’s out there in virtually any language, isn’t a very good use of my time.
There are a lot of programmers that don’t follow the KISS rule. Having configuration files in 6+ different areas is detrimental to ease of configuration of ANY product, no matter what the maturity level of the product is.
Any my worst pet peeve is lack of cleanup of unnecessary code/files for any given product. If you remove a need for a function/class, just get rid of the darn function/class, don’t leave it around for posterity’s sake (that’s what CVS/SourceSafe, etc. are for).
June 8th, 2006 at 10:50 pm
domain specific languages anyone? Ruby is very good for creating domain specific languages as opposed to PHP.
June 8th, 2006 at 11:19 pm
What the h*ll does that mean?
June 9th, 2006 at 3:42 am
I programmed in PHP more than five years and I can say that the PHP built-in functions are far less practical and useful than the Ruby built-in features (blocks, mixins, modules and a long etc.)
And, of course, things like file_get_contents don’t make PHP to be better than any other language… Harry, Can you do better to demonstrate me that PHP is better than Ruby?
June 9th, 2006 at 10:24 am
Nothing really. It’s just a pure display of fluff and non-sense.
June 9th, 2006 at 5:50 pm
Fenrir2 gave this as a code example for why he dislikes PHP.
$array = array(1, 2, 3); $ret = array(); foreach($array as $n) { $ret[] = $n * 2; } return $ret;If you want a single line you could do this…
array_walk($n = array(1, 2, 3), create_function('&$elem',$elem *= 2;'));It’s definately easier to understand than his prefered example of
[1, 2, 3].map{|n| n * 2}:)
June 9th, 2006 at 8:02 pm
Mark, you are kidding, right?
June 9th, 2006 at 10:50 pm
I guess so. The Ruby code is shorter and cleaner, and that’s the point of what I consider “good code”. :)
June 10th, 2006 at 3:27 am
To me the Ruby code is about as obscure as you can get and I have been programming in a number of languages since the late 1970’s.
Just because it is shorter doesn’t make it cleaner. In most cases the shorter it is the more confusing and obscure it will be. It also doesn’t mean it is any faster. :) I have seen some very short code that is slow and ponderous compared to code that is longer and easier to understand while being faster.
Just saying it is shorter makes it better is a misnomer when it comes to programming languages. I can make some very small code that is a pain for anyone to decipher.
When I look at anything written with Ruby I get the impression the language was created by someone with a bad case of dyslexia.
At the least, someone trying to pull a prank on programmers by making a language that isn’t that logical while using syntax that fosters more than a little obfuscation.
June 10th, 2006 at 4:13 am
I for did not claim that shorter is better. That’s not an absolute. But the claim has some merit to it, because simpler is better, and shorter is often simpler.
In your samples, the ruby version is hands down simpler. It’s not that the PHP version is longer, it is the fact that it includes script code in string literal, passed to a function which parses and executes a function?
The ruby version simple makes use of the built-in map algorithm. No extra parsing. To the point. And yes, shorter.
I’ve never programmed in ruby, but I do have experience with a lot of other languages. I don’t need to know every detail of ruby to recognize it a a very clean language (although I generally dislikes weakly typed/dynamically typed languages).
June 10th, 2006 at 4:32 am
No no no~, I didn’t say “shorter = cleaner”, I said the Ruby code is “shorter AND cleaner”. The point is “cleaner”. Given two pieces of “clean code”, the “shorter” one is preferred.
June 10th, 2006 at 3:41 pm
Or state it another way:
“clean” reduces the headache to understand the code
“short” reduces the boredom to understand the code
and when the two conflict, choose “clean” first, because boredom is better than headache :)
June 10th, 2006 at 3:48 pm
Well, Ruby is definately not cleaner code. It seems to be designed to confuse people on purpose. :(
June 10th, 2006 at 4:40 pm
But I think in your example the Ruby code is cleaner AND shorter :)
June 10th, 2006 at 9:18 pm
Change cleaner to confusing and I will agree. :D
June 11th, 2006 at 4:06 am
Is it possible to read a file over web in Ruby?
June 12th, 2006 at 4:24 pm
How do I check for a file’s existense via ruby without using exceptions? :)
July 19th, 2006 at 8:31 pm
I’ve studied Ruby for 2 weeks. After my hair became green, I moved back to PHP. IMHO Ruby sucks.
August 4th, 2006 at 7:10 pm