Almost-minimal filesystem based blog.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.0 KiB

  1. package App::WRT::Util;
  2. use strict;
  3. use warnings;
  4. use Carp;
  5. use Encode;
  6. use base qw(Exporter);
  7. our @EXPORT_OK = qw(dir_list file_put_contents file_get_contents);
  8. =over
  9. =item dir_list($dir, $sort_order, $pattern)
  10. Return a $sort_order sorted list of files matching regex $pattern in a
  11. directory.
  12. Calls $sort_order, which can be one of:
  13. alpha - alphabetical
  14. reverse_alpha - alphabetical, reversed
  15. high_to_low - numeric, high to low
  16. low_to_high - numeric, low to high
  17. =cut
  18. sub dir_list {
  19. my ($dir, $sort_order, $pattern) = @_;
  20. $pattern ||= qr/^[0-9]{1,2}$/;
  21. $sort_order ||= 'high_to_low';
  22. opendir my $list_dir, $dir
  23. or die "Couldn't open $dir: $!";
  24. my @files = sort $sort_order
  25. grep { m/$pattern/ }
  26. readdir $list_dir;
  27. closedir $list_dir;
  28. return @files;
  29. }
  30. # Various named sorts for dir_list:
  31. sub alpha { $a cmp $b; } # alphabetical
  32. sub high_to_low { $b <=> $a; } # numeric, high to low
  33. sub low_to_high { $a <=> $b; } # numberic, low to high
  34. sub reverse_alpha { $b cmp $a; } # alphabetical, reversed
  35. =item file_put_contents($file, $contents)
  36. Write $contents string to $file path. Because:
  37. L<https://secure.php.net/manual/en/function.file-put-contents.php>
  38. =cut
  39. sub file_put_contents {
  40. my ($file, $contents) = @_;
  41. open(my $fh, '>', $file)
  42. or die "Unable to open $file for writing: $!";
  43. print $fh $contents;
  44. close $fh;
  45. }
  46. =item file_get_contents($file)
  47. Get contents string of $file path. Because:
  48. L<https://secure.php.net/manual/en/function.file-get-contents.php>
  49. =cut
  50. sub file_get_contents {
  51. my ($file) = @_;
  52. open my $fh, '<', $file
  53. or croak "Couldn't open $file: $!\n";
  54. my $contents;
  55. {
  56. # line separator:
  57. local $/ = undef;
  58. $contents = <$fh>;
  59. }
  60. close $fh or croak "Couldn't close $file: $!";
  61. # TODO: _May_ want to assume here that any file is UTF-8 text.
  62. # http://perldoc.perl.org/perlunitut.html
  63. # return decode('UTF-8', $contents);
  64. return $contents;
  65. }
  66. =back
  67. 1;