What’s the difference between iterating over a file with foreach or while in Perl?

For most purposes, you probably won’t notice a difference. However, foreach reads each line into a list (not an array) before going through it line by line, whereas while reads one line at a time. As foreach will use more memory and require processing time upfront, it is generally recommended to use while to iterate … Read more

Run code for x seconds in Java?

The design of this depends on what you want doing for 15s. The two most plausible cases are “do this every X for 15s” or “wait for X to happen or 15s whichever comes sooner”, which will lead to very different code. Just waiting Thread.sleep(15000) This doesn’t iterate, but if you want to do nothing … Read more

When implementing an infinite loop, is there a difference in using while(1) vs for(;;) vs goto (in C)?

They are equivalent, even if you turn the optimizer off. Example: #include <stdio.h> extern void f(void) { while(1) { putchar(‘ ‘); } } extern void g(void) { for(;;){ putchar(‘ ‘); } } extern void h(void) { z: putchar(‘ ‘); goto z; } Compile with gcc -O0 gives equivalent assembly for all 3 functions: f: ; … Read more

Bash loop, print current iteration?

To do this, you would need to increment a counter on each iteration (like you are trying to avoid). count=0 while read -r line; do printf ‘%d %s\n’ “$count” “${line*//}” (( count++ )) done < test.txt EDIT: After some more thought, you can do it without a counter if you have bash version 4 or … Read more

How to break out of while loop in Python?

A couple of changes mean that only an R or r will roll. Any other character will quit import random while True: print(‘Your score so far is {}.’.format(myScore)) print(“Would you like to roll or quit?”) ans = input(“Roll…”) if ans.lower() == ‘r’: R = np.random.randint(1, 8) print(“You rolled a {}.”.format(R)) myScore = R + myScore … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)