classic-say.pl 917 B

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/env perl
  2. # Implements say command without Modern::Perl or anything extra.
  3. # Should support below Perl 5.10 comfortably. Supports variables, arrays and simple key=>value hashes (with a quirk).
  4. # Quirk: Prints hash element keys and values each in a new line. As a workaround, add a \ before the hash name. e.g. say \%arr2;
  5. # @source https://stackoverflow.com/a/31777816
  6. unless (eval "defined(&say)") {
  7. sub say {
  8. my %hash = %{$_[0]};
  9. if (scalar %hash > 0) { foreach (sort keys %hash) { print " $_ => $hash{$_}", "\n"; } }
  10. elsif (@_) { foreach (@_) { print $_, "\n"; } }
  11. else { print $_, "\n"; }
  12. }
  13. }
  14. # Examples:
  15. my $test='Just printing some text';
  16. my @arr = ('array item 1', 'array item 2');
  17. my %hash = (
  18. 'key1' => 'value1',
  19. 'key2' => 'value2',
  20. );
  21. say '---- String ----';
  22. say $test;
  23. say '---- Array ----';
  24. say @arr;
  25. say '---- Hash ----';
  26. say %hash;
  27. say '---- Hash (fixed) ----';
  28. say \%hash;