by simias · 5y ago · 0 comments
Perl has a lot of good ideas and things I find myself missing a lot when I use Python or JS (autovivification being probably #1) but IMO these one or two symbol magic variables would generally be improved if they were more descriptive, with maybe one exception for $_/@_.
Although I must admit reminiscing about this made me realize how much I miss Perl now that I'm forced to use Python for work.
Yet another horrible hack in Perl that for some reason is advocated for. Optional chaining / null propagation is a much, much better idea and shouldn’t have been any harder to implement.
Null propagation is nice too, but it doesn't address all the uses cases of autovivification when you have, say, a hash table of arrays and you want to insert a new entry in an array, creating it if it doesn't exist. In python you have to use setdefault which I always found clunky.
You can bind to a non-existing hash element (even multiple levels deep) and it won't exist until you actually assign to it:
my %h;
my $c := %h<a><b><c>;
say %h<a>:exists; # False
$c = 42;
say %h<a>:exists; # TrueMy 3rd rewrite was very stylized and, I felt, maintainable. Which proved to be true as I had to fix bugs in it.
I did weird stuff like using $whatever as the index into the @whatever array.
But I digress. On the <>, Little has argv so you can do
int main(string argv[]) { int i; string buf; FILE f;
if (defined(argv[1]) && streq(argv[1], "-") && !defined(argv[2])) {
while (buf = <STDIN>) bputs(buf);
} else {
for (i = 1; defined(argv[i]); i++) {
if (defined(f = fopen(argv[i], "r")) {
while (buf = <f>) puts(buf);
fclose(f);
} else {
fprintf(stderr, "unable to open '%s'\n", argv[i]);
}
}
}
return (0);
}but why would you want to when all of that is
int main(string argv[]) { string buf;
while (buf = <>) puts(buf);
return (0);
}I mean, come on, that's cat(1) in 8 lines of code.
edit: I need to learn hacker markup. My code looks like crap.
int main(string argv[]) { string buf;
while (buf = <>) puts(buf);
return (0);
}If you're already aware that ARGV exists, you'll guess that ARGF might be used in relation to it, and so when writing a CLI program that uses ARGV, you might wonder if ARGF could simplify your code and look up what it is/does.
These ultra terse shorthands make some sense in the shell because it's meant for interactive, write-only commands but a scripting language should be a little more verbose and consistent IMO.
while (buf = <>)
did. So I didn't want to invent a new syntax, there is way too much of that going on, I like C, I like perl, pull the useful stuff from each and move on.
I freely admit it's not how everyone would do it.
I think <> as a fancy readline and _ as a default/throwaway variable does really improve readability and lowers the mental load of understanding programs.