Perl Programming/Keywords/each

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Previous: dump Keywords Next: else

The each keyword[edit | edit source]

each returns a two-element list consisting of the key and value for the next element of a hash, if called on a hash in list context. In Perl 5.12 and later only, it returns the index and value for the next element of an array. For older Perl versions, this is considered as a syntax error. When called in scalar context, it returns only the key (not the value) in a hash, or the index in an array.

Syntax[edit | edit source]

  each ARRAY
  each EXPRESSION
  each HASH

Examples[edit | edit source]

The code
  while (($key,$value) = each %ENV) {
    print "$key = $value\n";
  }
returns the environment as key-value pairs, separated by an assignment sign, like:
 USERPROFILE = C:\Users\<user name>
 USERDNSDOMAIN = <domain name>
 […]
 HOMEDRIVE = U:
 PATH = C:\Programms\Perl\site\bin;…
 […]
 SYSTEMDRIVE = C:
 […]
 USERNAME = <user name>
 […]


See also[edit | edit source]

Previous: dump Keywords Next: else