learn_gnuawk icon indicating copy to clipboard operation
learn_gnuawk copied to clipboard

Awk exercises Q:58/88 imprecisely defined

Open FabijanC opened this issue 1 year ago • 1 comments

The exercises reads:

The input file nums.txt contains a single column of numbers. Change positive numbers to negative and vice versa. Solution should use the sub function and shouldn't explicitly use the if-else control structure or the ternary operator.

The reference solution indeed relies on sub:

awk '!sub(/^-/, ""){sub(/^/, "-")} 1' nums.txt

But the most elegant solution would be simply:

awk '{ print -$0 }' nums.txt

In fact, the elegant solution would work correctly in case the input file contained a zero value (0), whereas the reference solution would substitute 0 with -0.

Perhaps the conditions of the exercise need to be defined differently if the point is to really rely on sub and its return value.

FabijanC avatar May 21 '24 20:05 FabijanC

Hmm, yeah. The main intention was to force the use of sub function and its return value. I'll probably try to come up with a different string manipulation data instead of relying on numbers that could be solved in a simpler way.

Thanks!

learnbyexample avatar May 22 '24 03:05 learnbyexample