简体   繁体   中英

why do I need to initialize variable in begin block

I have run the following code :

awk 'BEGIN{ color["one"]="red"; color["two"]="orange";print color["one"] }'

and got

red

However, when I execute the following two codes :

awk 'BEGIN{ color["one"]="red"; color["two"]="orange"}{print color["one"] }'

and

awk '{ color["one"]="red"; color["two"]="orange";print color["one"] }'

the execution does not seem to work. Why can't I put color["one"] in the body block for the first not working code? Also, why do I have to put color["one"]="red"; color["two"]="orange";print color["one"] color["one"]="red"; color["two"]="orange";print color["one"] in the begin block? Thank you.

Yes, it is expected behavior since BEGIN section in awk executed before reading an Input_file so it does not require you to pass any Input_file name hence your 1st awk works. But in your other awk you closed the BEGIN section and then opened a main block by {...} so it requires a Input_file to execute it.

See following from man awk page too:

BEGIN and END are two special kinds of patterns which are not tested against the input. The action parts of all BEGIN patterns are merged as if all the statements had been written in a single BEGIN block. They are executed before any of the input is read. Similarly, all the END blocks are merged, and executed when all the input is exhausted (or when an exit statement is executed). BEGIN and END patterns cannot be combined with other patterns in pattern expressions. BEGIN and END patterns cannot have missing action parts.

Your 1st awk :

awk 'BEGIN{ color["one"]="red"; color["two"]="orange";print color["one"] }'

After BEGIN section no statements are given so it works expected and gives red as output.



Your 2nd awk : Let us divide it in 2 parts

1st part (for understanding):

awk 'BEGIN{ color["one"]="red"; color["two"]="orange"}

2nd part (for understanding):

{print color["one"] }'

So 1st part is BEGIN section and 2nd part is main block which expects an Input_file is to be passed to awk program.

Answer for why initializing variables or arrays in BEGIN section: For your question why one has to initiate variables or array in BEGIN block is since BEGIN section gets executed before main block when Input_file is being read, so it is good to have all initialization of variables and arrays there to avoid them re-initiating or initiating them with a condition (which will be checked each time each line is being read). That is why it is recommended IMHO to initialize them in BEGIN section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM