amarao: (Default)
amarao ([personal profile] amarao) wrote2022-05-01 12:31 pm

Учи баш, учи баш

Вот, я опять узнал что-то новое.

! command позволяет инвертировать код возврата. Казалось бы, тривиально, но с учётом мнения readline по поводу '!' у меня было табу насчёт восклицательных знаков в шелле.

[personal profile] ex0_planet 2022-05-01 01:27 pm (UTC)(link)
$ function 42() { return 42; }
$ 42 ; echo $?
42
$ ! 42 ; echo $?
0
$ ! ! 42 ; echo $?
42


Несколько неожиданный даже для меня самого результат: я думал что в какой-то момент оно таки превратится в некий эквивалент bool, и там будет как в сишке — 0 => true => 0, x => false => 1 (для любого ненулевого x).
juan_gandhi: (Default)

[personal profile] juan_gandhi 2022-05-01 02:16 pm (UTC)(link)

OMG. It's complicated, is not it? How do they keep 42? Seems like the script is compiled (and optimized) before running. Weird, weird. Not that I don't like it. Enjoying it.

[personal profile] ex0_planet 2022-05-01 03:18 pm (UTC)(link)
Yep, it is more complicated than I thought it would be.

Compiled? Not necessarily, IMO they have some sort of expression context (kinda like Perl, after all it is from the same era :)). So, a '! ! 42' evaluates in some sort of numeric context (there is an implicit assignment to $!); in the context of 'if .. then' expression it is evaluated as boolean. Makes sense, huh!?
juan_gandhi: (Default)

[personal profile] juan_gandhi 2022-05-01 06:35 pm (UTC)(link)

Yes, but one had to reduce ! ! to nop, otherwise how does it know that ! 0 should be 42?