Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Note that $_ is an alias to the list value, so it can be used to modify the elements of the LIST. While this is useful and supported, it can cause bizarre results if the elements of LIST are not variables. Using a regular "foreach" loop for this purpose would be clearer in most cases.

While Although it is supported, using map() to modify a list in - place can lead to surprises in maintainability , and is thus forbidden.

Many other list functions provide similar functionality, using a block on various list elements. The grep() function is one such example, as are the first() and reduce() functions in List::Util and all of the functions in List::MoreUtils.

Finally, the sort() function also provides aliases to its comparison blocks, so a comparison block for sort() must also not modify its variables.

...

This noncompliant code example reads the /etc/passwd file , and lists each user that uses all users who use /bin/sh as their login shell.

Code Block
bgColor#ffcccc
langperl
open( PASSWD, "<", "/etc/passwd");
@users = <PASSWD>;
@shell_users = grep +(s|/bin/sh||), @users;
foreach $user (@shell_users) {
  print "Shell User: $user";
}

However, since because the grep() block removes /bin/sh from any input line that contains it, it modifies the @users list so that no user has /bin/sh!

Compliant Solution grep()

This compliant colution solution does the same thing , but does not modify the @users array.

...

If any error occurs, the program calls the croak() function, passing it a string that includes both the source file being opened , and the $! variable, which contains a system error string based on the value of errno. errno, which is set to a useful value when the open(2) or close(2) functions fail.

...