Now that I can edit CoffeeScript files, what can I do with them? Well, I can run them just by adding a shebang line with coffee on it
#!/usr/bin/env coffee
console.log "Hello, World!"
If I put that in a file called hello.coffee, then I can run it with
$ ./hello.coffee
Hello, World!
and get just what you think. How about if we define a hello
function and call it with whatever is passed in on the command line?
#!/usr/bin/env coffee
hello = (name = "World") -> "Hello, #{name}!"
console.log hello(process.argv[2])
If I call it with a name, I get a personal greeting. Otherwise, I get the generic greeting.
$ ./helloyou.coffee oylenshpeegul
Hello, oylenshpeegul!
$ ./helloyou.coffee
Hello, World!
We would probably write this in Perl as
#!/usr/bin/env perl
use v5.14;
use warnings;
my $name = shift // 'World';
say "Hello, $name!";
but it's really more analogous to
#!/usr/bin/env perl
use v5.14;
use warnings;
sub hello {
my $name = shift // 'World';
return "Hello, $name!";
}
say hello($ARGV[0]);
We are calling the hello
subroutine with an element from the argument list which may not be there. CoffeeScript's normal behavior for subroutine arguments is like Perl's "defined or" (//
). We can see this if we look at the JavaScript for it.
$ coffee -c helloyou.coffee
$ cat helloyou.js
(function() {
var hello;
hello = function(name) {
if (name == null) {
name = "World";
}
return "Hello, " + name + "!";
};
console.log(hello(process.argv[2]));
}).call(this);
Note that we're using argv[2]
. This is apparently a Node thing; argv[0]
is the interpreter (coffee), argv[1]
is us (./helloyou.coffee), so our argument list starts with argv[2]
.
Speaking of Node, let's use its http
module to try our hand at retrieving a Futurama quote from Slashdot.
#!/usr/bin/env coffee
http = require 'http'
ucfirst = (str) ->
str.substr(0, 1).toUpperCase() + str.substr(1)
http.get host: 'slashdot.org', (res) ->
for c in ['fry', 'bender']
k = "x-#{c}"
if res.headers[k]
console.log "#{ucfirst(c)}: #{res.headers[k]}"
I'm doing a GET here (Is this a waste? I don't know how to do a HEAD.) and then looking for the Fry and Bender response headers, just as we did in dotperl. I don't have a ucfirst
in CoffeeScript, so I wrote one using JavaScript's toUpperCase
method.
$ ./futurama.coffee
Fry: Where's Captain Bender? Off catastrophizing some other planet?
Keen! I'm really enjoying CoffeeScript!
Recent Comments