15 ms·
Perl code that is syntactically correct only on Fridays
- 77pt77 5y agoI really feel sorry for these people wasting their lives for decades engaging in mental onanism like these perl gotchas. Randal has been doing nothing but this for at least 20 years.
- raxxorrax 5y agoI have written code that only works in winter because of daylight saving times and some unfortunate date conversions, but having a temporary correct syntax is really a new high.
- chaosite 5y agoI have written code (at work) that crashes when the moon is in a specific phase. I had a "switch(moon_phase)" and forgot one of the cases... And the Android app was in debug mode, so any uncaught exception brought the whole thing down.
- tupac_speedrap 5y agoHaving the code crash every full moon would be pretty cursed tbh.
- grishka 5y agoNot nearly as cursed as two parent comments, but there was a widespread problem in my very popular Android app. The relative date formatting function worked incorrectly for many users, it was off by one hour. It turns out that when Russia (where most of our users were) had abolished DST, and then changed timezones a couple of times, people got really confused. Since Android's timezone data is part of the system, it was basically set in stone. Most of the users didn't choose the timezone with the correct offset, but instead set their time an hour forward so the incorrect timezone and incorrect unixtime cancel each other out for a "correct" displayed time. I ended up getting the known correct unixtime from the server to try to guess which timezone offset the user actually meant and correcting the result of System.currentTimeMillis() and my formatting for that.
- nicoburns 5y ago> I have written code that only works in winter because of daylight saving times and some unfortunate date conversions Not sure where you are located, but this can be particularly bad in the UK where winter time happens to coincide with UTC.
- DocTomoe 5y agoLet's be pedantic about this, because this is one of the very few areas where pedantry matters: GMT ("British Winter Time") is NOT UTC, and it can differ from UTC up to 0.9 seconds. GMT is a time zone (corresponding to UT1). UTC is a time standard.
- jfk13 5y agoTo be pedantic, this is an area where pedantry occasionally matters. For the vast majority of (casual) usage, it doesn't.
- gerikson 5y agoIndeed. I get invites from people from the UK who simply refer to the current local time (GMT or BST) as "GMT". It just means current London time to them.
- ycombobreaker 5y agoSame happens in the US, people use EST/EDT interchangeably (and incorrectly) when they mean Eastern timezone. Or Central/Mountain/Pacific.
- nicoburns 5y agoOk, fair enough. But it's close enough that it's very easy for anything that isn't working with second-level granularity to seem like they're working only to break as soon as the time switches BST.
- dane-pgp 5y agoI appreciate your pedantry, and I wonder if you know of a widely used computer system which genuinely implements the GMT time zone as something different from UTC+0. There may be some niche astronomical or legal(?) applications which have to keep track of the potential 0.9 seconds skew, but my impression is that any app which claims to support a "GMT" (or Europe/London) option is actually only supporting "GMT-ish".
- hyperman1 5y agoAs a part of a release always got borked, I wrote a small bash script that took currently deployed files, archived them to rollback_dateandtime.tgz, then put the freshly released files in its place. It turns out we never did a release before 10:00, because it ran fine for a few years, but the regex constructing the filename could not deal with hours consisting of 1 number. Oh well, never write production shell scripts while your platform is burning. The fix is literally 1 character, but I only get access when production burns. So I was not allowed to change it and the owner does not want to implement it and file all release paperwork it entails. Instead, mgmt forbid this type of release before 10:00.
- gpvos 5y agoThis is why we can't have nice things.
- dotancohen 5y agoI have once heard of some software that would crash on some Wednesdays. Apparently Wednesday is the longest day name, and it was overflowing some buffer. But only if the day of the month was 10 or above, because the strings 1-9 still fit in the buffer.
- profmonocle 5y agoThe first iPhone app I wrote back in college would crash if you used it in a time zone with a positive UTC offset. I can't even remember why.
- cube00 5y agoAnother great reason not to deploy on Friday.
- bitfoxtop 5y agoperl? write once, read forever.
- athenot 5y agoThis leverages Perl's BEGIN block which runs before the main part of the code. I suppose the same fun could be had in other languages: if day_of_week is "Friday" eval(piece_of_incorrect_code) else do_sane_operation
- yodon 5y agoMoral quandary of the morning: Do I point out the sign error or do I just say please don't merge this?
- saba2008 5y agoMost other languages would require `eval` and having incorrect code as syntactically correct string literal. But because Perl is parsed as it is executed, incorrect code raises syntax error only when it is reached by execution.
- cestith 5y agoPerl is not parsed as it is executed. It is compiled to opcodes then run. The BEGIN block, however, explicitly runs code at compile time. It is literally compiling different code on different days, then attempting to run it.
- RandalSchwartz 5y agoTechnically not opcodes, but internal Data Structures. A serializer was written for that, to permit ".pmc files".
- cestith 5y agoOh, hey, Randal. Thanks for the correction. Looking forward to the next time we can have steaks and Scotch.
- JohnDeHope 5y agoRight, the beauty of this is that it's a syntax error he's produced. Sure any language can write code to produce a runtime error under any condition at all. And a lot of languages have features that allow them to run code at compile time, and similarly produce errors then too. But those languages don't allow you to ruin the syntax of the language. I guess it's something that requires macros. Would it be safe to say that any language with macros can do this? Or is there something even more interesting with perl going on here?
- fouronnes3 5y agoPro tip: add test cases to your CI runs with modified system date.
- WesolyKubeczek 5y agoThe thing is, you need to have a pretty corkscrew mind to think about cases like this. What date to change to? Far into the future? Far into the past? To a weekend? To a DST change? To Friday the 13th? To a US holiday? To a Muslim, Jewish, Chinese, Soviet, Albanian holiday? To a particular weekday? To Hitler's birthday? What if it's Lenin's? To that one day my coworker was depressed because the boss denied him a raise and talked shit to him? Too many possibilities. And your timebomb might be in one of your dependencies to boot.
- zanderwohl 5y agoI feel obligated to link "Falsehoods programmers believe about time" - I think it's best to just get a trusty library instead. https://gist.github.com/timvisee/fcda9bbdff88d45cc9061606b4b923ca https://gist.github.com/timvisee/fcda9bbdff88d45cc9061606b4b...
- JohnBooty 5y agoAmen. Worked for a few years at a company with a medium-sized codebase whose tests only worked before 6PM. (Run the tests later than that, and you wind up with some timeframes that span calendar days and therefore break things. Was the underlying code broken, or the tests, or both? Who knows!!) Was never allowed to fix and investigate. Or to be specific, we were never given the time to fix it. Management simply didn't see it as a problem. In my younger days I would have gone all HERO HACKER and fixed it anyway on my own time. But now, I know how that turns out. You waste a bunch of evenings fixing it, and usually introduce some other regressions, and you get zero glory and lots of blame. Best case scenario is no regressions and zero glory. So, screw it. Old-and-jaded me never lifted a finger. If the company doesn't care, why should I? But, that is an excellent protip. If you are working on a team that actually values things that work. Time/date dependent code is very tricky to get right, especially when multiple time zones are involved. If your test suite doesn't cover multiple possibilities, your code is nearly guaranteed to be wrong. It's not even like you have to write brand-new, cleverer tests. Just "brute-force" it, assuming your tests are performant: before: some_tests after: [time_zone_1, time_zone_2, time_zone_3].each do |tz| [time_of_day1, time_of_day2, time_of_day3].each do |tod| some_tests(tz, tod) end end ...that kind of thing. That's what I did when I wrote new code at that company, even though I refused to fix the legacy stuff. My tests were faster, too. Almost like I knew what I was doing...
- saba2008 5y agoSomewhat related: Perl Cannot Be Parsed: A Formal Proof (2008) https://news.ycombinator.com/item?id=5770531 https://news.ycombinator.com/item?id=5770531
- rabbits77 5y agoWell, to be a little pedantic, Perl cannot be statically parsed, since some constructs require runtime context. If it could not be parsed it could never work! And this is totally OK in my book, I use Perl for prototyping ideas and an expressive language that allows creativity from me the programmer is a feature as it promotes looking at a problem from multiple aspects.
- avgcorrection 5y ago“Cannot be X” most often means “in the general case”. (In the context of computability.)
- lmm 5y ago> Well, to be a little pedantic, Perl cannot be statically parsed, since some constructs require runtime context. If you're going to be pedantic, it's important to be correct; there's no such thing as dynamic parsing. > If it could not be parsed it could never work! What's the logic here? An interpreter doesn't have to operate on an AST, a language doesn't have to have a nontrivial grammar (consider Brainfuck). Perl is just a language in the same category: it doesn't have a (true) nontrivial AST, it doesn't have a (true) nontrivial grammar, and it can't be (truly, nontrivially) parsed.
- samatman 5y ago> there's no such thing as dynamic parsing As long as we're indulging in pedantry, this is incorrect presuming dynamic means what it usually means. Any regular expression constructed at runtime contradicts you. Modifying your core parser at runtime though, who would do such a thing? Other than reader macros in Common Lisp I mean. Are we going to argue this means Common Lisp doesn't parse if we add reader macros at runtime? A peculiar argument. Now. Should we talk about whether doing that is a good idea? A lovely and separate conversation. I agree with GP that since Perl will spit out a parse tree, it does in fact parse, and since it's not static, well, it's dynamic. Which we can prove by, I dunno, writing some Perl which only parses on Fridays. Right?
- johnnyo 5y agoI had an intern once who wrote similar code. They confused 12 hour and 24 hour clocks, so the code would break after lunch. Unfortunately, the intern only worked the mornings, so it took several days of back and forth before the bug could be finally put to rest.
- anned20 5y agoIf you tried, you couldn't even come up with this.
- RandalSchwartz 5y agoI could. :)
- alisonatwork 5y agoFantastic. We had a similar problem with test code that always worked on a remote team's computers during their work day but failed when we got into the office and tried to run it in a different timezone.
- allenu 5y agoI've seen something similar where some automated unit tests always passed and when I tried to run it locally would always fail. After digging around I realized it was making assumptions about the timezone it ran in, which was on the east coast, whereas I was on the west.
- pc86 5y agoReminds me of an app I worked on a while ago where both the server it was running on and the datetimes in the database had to be in a specific time zone. Change either (including changing both to an identical but different TZ) and the app just failed to run.
- vidarh 5y agoI've had to fix any number of test suite bugs as well as regressions that happened because the people who wrote the tests had ensured the test suite didn't (most of the time) test what they thought it would by relying on date arithmetic from current date and time...
- jakub_g 5y agoSemi-related HN classic: "Openoffice can’t print on Tuesdays" https://news.ycombinator.com/item?id=8171956 https://news.ycombinator.com/item?id=8171956 A handful of curated weird stories like this: https://500mile.email/ https://500mile.email/
- WesolyKubeczek 5y agoWhy only things like these float up to the front page, and not elegant and/or wholesome things written in Perl?
- JohnHaugeland 5y agopossibly because no such thing exists
- recrof 5y agobecause of your taste of perl syntax? that's only thing that makes it different from any other scripting language.
- gerikson 5y agoPerl is like life - it contains both good and bad. And good things in Perl don't get noticed because they Just Work.
- layer8 5y agoRight, it’s elegant Perl that would be newsworthy, not gruesome Perl. (Tongue-in-cheek, I’m actually rather partial to Perl.)
- sundarurfriend 5y agoBecause with its declining popularity, most people here are unfamiliar with the language except for its meme status as "that weird line noise language". Things that confirm pre-existing beliefs are easy to accept and upvote, whereas good Perl code would require (a) some actual thinking, and (b) challenging the socially accepted narrative - both of which are relatively much harder.
- WesolyKubeczek 5y agoGood Perl code would also look pretty boring, almost like enterprise Java. I'd wager that all code that "just works", in any language, looks bland and predictable. But I'd rather have that than cute and clever any day.
- praptak 5y agoIn similar vein: parsing C++ is literally undecidable: https://blog.reverberate.org/2013/08/parsing-c-is-literally-undecidable.html https://blog.reverberate.org/2013/08/parsing-c-is-literally-... You can't even decide if a particular "*" is multiplication or a pointer dereference until you resolve templates, which is Turing-complete.
- vidarh 5y agoUnless something has changed a lot, C++ templates at least only used to be Turing complete if you assume you're allowed unlimited recursive template applications, and compilers were free to restrict that (and did). Has that changed? In theory I agree with you that this is horribly ugly - I very much prefer simple grammars (the irony being my favourite language to use is Ruby, which has an atrocious grammar). In practice these parses are rarely that hard to resolve.
- steerablesafe 5y agoWell, C++ now has constexpr functions that can run in compile time, and do basically arbitrary computation. But it also has implementation limits.
- praptak 5y agoIt's not the undecidability itself that is the problem though. The undecidability is just an indicator how horribly complicated C++ is to compile. You cannot even construct the full parse tree before evaluating a mini-language that is Turing complete. Related article: why C++ compilation is slow (https://digitalmars.com/articles/b54.html https://digitalmars.com/articles/b54.html)
- vidarh 5y agoI have a half-finished Ruby compiler sitting around, so I'm a bit jaded when it comes to how complicated something is to compile. C++ is complex, but at least it's reasonable well specified.
- ncmncm 5y ago
- G3rn0ti 5y agoThis is how it works: BEGIN { # an execution block that runs when the module is compiled *f = # assigns to the symbol "f" inside the symbol table ... (localtime->wdayname eq 'Fri') # is it Friday? ? sub() {} # ... on friday an anonymous subroutine taking no arguments : sub {}; # ... on every other day a subrouting taking arguments } # closes the execution block # The following line executes the subroutine "f" and divides the result by 1 on fridays # but on other days causes the interpreter to trigger a syntax error because it expects # f to take an argument list "(...)" but receives an operator "/". f/1;#/+
- metalliqaz 5y agoThank you for this. I hate trying to read Perl so much. What is the "#/+" for?
- jwilk 5y agoOn Fridays, it's just a comment. Otherwise, "f/1;#/+" is equivalent to something like: f(/1;#/ +) where /1;#/ is a regexp matching operator, and stray + triggers syntax error.
- space_ghost 5y agoFlavor? "#" starts a comment, so the "/+" characters are ignored by the interpreter.
- deleted 5y ago[deleted]
- G3rn0ti 5y ago> What is the "#/+" for? I am sure this is not necessary for the behavior described. It's just a comment. BTW: I am working for a company still maintaining a large Perl code base and I think this is rather obscure stuff. You rarely need to run something at compile time, hack the symbol table and you almost never need "sub() {}" to define subroutines with an empty "prototype". If I saw this in a code review I would most definitely had a closer look and would decline a PR if that was unnecessary. Meta programming should not be done lightheartedly and better serves a serious purpose.
- draw_down 5y ago
- pera 5y agoheh as soon as I saw the ternary expression I recalled the bug report I submitted some years ago: https://rt-archive.perl.org/perl5/Ticket/Display.html?id=130343 https://rt-archive.perl.org/perl5/Ticket/Display.html?id=130...
- markstos 5y agoJust reading the headline gave me traumatic flashback to a customer project for a winter sports brand that broke on April 1st after not being modified for months prior to this. You guessed it: There was a sleeper bug detonated by the date change. Pain the butt to track down in Perl code that was generating an Excel spreadsheet cell-by-cell.
- alkaloid 5y agoSomeone found my telco code.
- gvb 5y ago<pedantic> The code is never syntactically correct however the syntax error is not identified by the Perl interpreter on Fridays. </pedantic>
- reneberlin 5y agoI don't get it! It is clearly written in the code, that the progam should behave this way. Is the proof, that perl is capable of this behaviour?! I don't get it - what is the point? I read all the comments and still don't get it. What am i missing?
- bachmeier 5y agoWas going to say the same thing. I thought it would be something wrong with the language. If you're going to write code that's different depending on the day of the week...meh.
- JohnHaugeland 5y agothey made a branch where one side is defective and the other isn't they only follow the non-defective side one day a week because perl doesn't forward analyze, it never sees the error on other days, and doesn't fail the presentation is false. this code is always wrong. it's just that the bug is only visible under certain conditions.
- wutbrodo 5y agoYou can write code in any language that fails at runtime depending on the day. What's notable about this is that its _syntactical correctness_ depends on the day, which is not possible to achieve in many languages. What's being noted is the degree of flexibility that Perl has with respect to its execution environment. Though if you include preprocessors, you expand the number of languages for which you can do something similar.
- iLoveOncall 5y agoWhat makes it "special" here is the fact that it will COMPILE only on a friday. It's not a runtime error but a compile time error. Because yes otherwise I would agree that it's doable easily in every single language.
- ghayes 5y agoBut isn’t this possible with any language that has a pre-compilation step? Perl is certainly conflating its passes (as explained by other comments above), but in rust you could add a check in build.rs or use macros in C to accomplish the same, right?
- me_again 5y agoI had a program once which failed every time it was 8 or 9 minutes past the hour and worked the rest of the time. It parsed a string containing the time and sscanf treats "08" and "09" as invalid octal numbers. Argh.
- mrspuratic 5y agoBeen there, a TCL web script, IIRC. This led to religious processing of input with "regsub" (this predated TCL 8). Yuck. Also once fixed an inherited awk script that malfunctioned at the end of year: a hardcoded month name array with November missing. To this day I always populate any such lookup with a loop and strftime() or appropriate.
- JohnHaugeland 5y agoThis code is always syntactically incorrect. It is merely that the problem branch is only occasionally followed.
- didip 5y agoWow. Do I need more reasons to hate perl? Yes, apparently.
- brian_herman 5y agopython: import datetime if datetime.datetime.now().weekday() == 3: 1/0
- jwilk 5y agoOnce you fix the indentation, this code is always syntatically correct; it just happens to raise an exception on Thursdays.
- bastardoperator 5y agoI worked with Randal L. Schwartz for several years in the Los Angeles area. I was already doing Perl but getting an opportunity to see his code and ask him questions was something that changed my career for the better. Thanks Merlyn!
- RandalSchwartz 5y agoHave you seen my "parse JSON in a single Perl Regex"? https://www.perlmonks.org/?node_id=995856 https://www.perlmonks.org/?node_id=995856
- hondo77 5y agoDitto, except s/several/a couple of/
- pvg 5y agoIt's mentioned in the source but it's based on this: https://www.perlmonks.org/index.pl?node_id=44722 https://www.perlmonks.org/index.pl?node_id=44722
- gfldex 5y agoAs a sister language of Perl, Raku can do the same trick. constant &s = (now.DateTime.day-of-week == 7) ?? sub () {} !! sub (|) {}; constant c = s(42); Constants are evaluated at compile time. Here we define a sub that takes no argument or any number of arguments depending on the day of the week (In Raku we start at 1 for monday to avoid ending the universe by deviding by 0). While binding the return value of s(42) to a constant we force execution of that sub at compile time. Thusly, we create a program that can not be executed when compiled on sundays. This is reasonalbe, because by heavenly mandate we are bound to rest on that day. Modules are precompiled, programs are not (yet). So to make this really depend on the day of compilation we have to put it into a module (for now).
- edgyquant 5y agoI miss Perl and it’s community from the early-mid 2000s. Sure it was bad for those who have to maintain but trying to create the shorted and most unreadable possible was a fun pastime.
- deleted 5y ago[deleted]
- jordanmorgan10 5y agoGah why did I take up programming for a living :|
- kazinator 5y agoC code in similar spirit: $ gcc weird-0.c $ ./a.out No output from weird-0 $ gcc weird-1.c $ ./a.out foo(42) Output from weird-1. What is weird-0? $ cat weird-0.c #include <stdio.h> void foo(int x) { printf("foo(%d)\n", x); } int x = 42; int main(void) { #if __LINE__ % 2 == 0 typedef int foo; #endif foo(x); return 0; } OK, how does weird-1 differ from weird-0? One blank line! $ diff -u weird-0.c weird-1.c --- weird-0.c 2022-02-16 12:09:29.565563802 -0800 +++ weird-1.c 2022-02-16 12:09:38.185718722 -0800 @@ -7,6 +7,7 @@ int x = 42; + int main(void) { #if __LINE__ % 2 == 0 Explanation: { #if __LINE__ % 2 == 0 // If this line number is even typedef int foo; // foo is a typedef name for int #endif foo(x); return 0; } If foo is a typedef name for int, then "foo(x)" is syntactically declaration. It's declaring a local variable x to be of type foo, alias for int. If the typedef is missing, then foo(x) refers to the file-scope identifiers: the function foo and variable x. It is a call to foo passing the value 42 of x. The preprocessor conditional could easily introduce a syntax error, but the issue in Perl is that a parsing decision (how the / token is lexically categorized) is made based on the compile-time value assigned to f. This is similar to the compile-time meaning of foo we are setting up with the presence or absence of the typedef.
- kazinator 5y agoWith a small change to the weird-0 and weird-1 programs: $ gcc -O2 -Wall -W weird-0.c weird-0.c: In function ‘main’: weird-0.c:15:7: warning: unused variable ‘x’ [-Wunused-variable] foo(x); ^ $ gcc -O2 -Wall -W weird-1.c weird-1.c: In function ‘main’: weird-1.c:16:3: error: too few arguments to function ‘foo’ foo(x); ^~~ weird-1.c:3:6: note: declared here void foo(int x, int y) ^~~ The change is in the foo function: void foo(int x, int y) { printf("foo(%d, %d)\n", x, y); } The call is now erroneous, and with the increased compiler optimization level and diagnostics, the declaration case diagnoses x being unuse
- Leherenn 5y agoI have seen some code that would fail based not on time but location. Once we had a client from the Netherlands that complained about a bug that we could not reproduce. We tried to reproduce it by simulating his position, but to no avail. Turns out he was in a very specific, slightly depressed, area that was a few centimetres below mean sea level and that the code didn't like negative altitudes. Another one only happened in the southern hemisphere. Given we were based in Europe and it was winter, we asked whether we could do some more tests in Australia to make sure there were no more bugs, but sadly it was denied.
- Drblessing 5y agoWhat about Phase-Of-The-Moon code?
- vardump 5y agoSo many things compile / work well on Friday, just before weekend...
- justintoon 5y agoAm I literally the only person who sees the pun against “His Girl Friday?” Maybe it wasn’t intentional but that’s literally the first thing I thought of.
- jwilk 5y agoIt wasn't intentional. Can you explain the pun?
- keybuk 5y agoUbuntu Bug 255161: Openoffice can’t print on Tuesdays (launchpad.net) https://news.ycombinator.com/item?id=8171956 https://news.ycombinator.com/item?id=8171956