This post originated from an RSS feed registered with Ruby Buzz
by Andrew Johnson.
Original Post: Use the DATA handle
Feed Title: Simple things ...
Feed URL: http://www.siaris.net/index.cgi/index.rss
Feed Description: On programming, problem solving, and communication.
One thing I recommend to newcomers to both Perl and Ruby is to make use of
the DATA file(handle/object) for explorative purposes. It is quite useful
both in the contexts of language exploration and solution-space
exploration.
The basic idea is that within your Perl or Ruby script, any text after the
special __END__ token is available to be read into the program via a
preopened filehandle/object named DATA (in both languages). In Perl, the
token may also be called __DATA__.
Here’s a simple example (Perl and Ruby side by side):
#!/usr/bin/perl -w #!/usr/bin/ruby -w
use strict;
while (my $line = <DATA>) { while line = DATA.gets
my @arr = split /:/, $line; arr = line.split(/:/)
print join '|', @arr; print arr.join('|')
} end
__END__ __END__
abc:def:ghi abc:def:ghi
123:456:789 123:456:789
Note: the __END__ token must be flush with the left margin in Ruby
code.
There are many ways this can be usefully used, but for my exploratory
purposes it is only half of the equation. The other half is your text
editor (or perhaps IDE). Many text editors can be configured to run the
text (or some selected portion thereof) of the current buffer through an
external program (usually as a filter). If you are writing Perl or Ruby
code, that external ‘filter’ can be the Perl or Ruby
interpreter, and you can arrange for the output to be displayed in another
window (pane, buffer, whatever).
For example, I have the following in my .vimrc file:
Now hitting the F9 or F10 key sends the selected text to the interpreter,
captures the output into a special file, and opens that file in a new
buffer window. Both Ruby and Perl can recieve scripts via STDIN, and both
leave everything following the __END__ token to be read via the DATA
handle.
This means I can have a buffer window open to play around with a new
language element or feature, or to explore possible solutions to a problem.
And if that problem requires some data reading/munging/parsing, I can paste
in some representative lines of data and have one-key convenience for
trying out various snippets of code.