Advertisement
saltycracker

MyExporter

Mar 29th, 2020
587
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.55 KB | None | 0 0
  1. ##### main.pl
  2. #! /usr/bin/env perl
  3.  
  4. use lib q<.>;
  5.  
  6. use warnings;
  7. use strict;
  8. use utf8;
  9. use feature qw<say>;
  10.  
  11. use MyFuncs qw<add minus multi divide>;
  12.  
  13. say add(12, 34);
  14. say minus(12, 34);
  15. say multi(12, 34);
  16. say divide(12, 34);
  17.  
  18. # say "\n";
  19.  
  20. # for my $key (sort keys %::) {
  21. #   say "${key}=>", $::{$key};
  22. # }
  23.  
  24. exit(0);
  25.  
  26. ##### MyFuncs.pm
  27. package MyFuncs;
  28.  
  29. use 5.006;
  30. use strict;
  31. use warnings;
  32.  
  33. use MyExporter qw<import>;
  34.  
  35. our @EXPORT_OK = qw<add minus multi divide>;
  36.  
  37. sub add {
  38.     my ($a, $b) = @_;
  39.     $a + $b;
  40. }
  41.  
  42. sub minus {
  43.     my ($a, $b) = @_;
  44.     $a - $b;
  45. }
  46.  
  47. sub multi {
  48.     my ($a, $b) = @_;
  49.     $a * $b;
  50. }
  51.  
  52. sub divide {
  53.     my ($a, $b) = @_;
  54.     die "Can't divide by $b" if $b == 0;
  55.     $a / $b;
  56. }
  57.  
  58. 1; # End of MyFuncs
  59.  
  60. ##### MyExporter.pm
  61. package MyExporter;
  62.  
  63. use 5.006;
  64. use strict;
  65. use warnings;
  66. use feature qw<say>;
  67. use List::Util qw<any>;
  68.  
  69. sub import {
  70.   my ($pack, @funcs) = @_;#MyExporter @funcs
  71.   my ($c_pack) = caller;#MyFuncs
  72.  
  73.   if (any{$_ eq 'import'} @funcs) {
  74.     no strict qw<refs>;
  75.  
  76.     *{"${c_pack}::import"} = \&{"${pack}::myImport"};
  77.   }
  78. }
  79.  
  80. sub myImport {
  81.   my ($pack, @funcs) = @_;#MyFuncs @funcs
  82.   my ($c_pack) = caller;#main
  83.  
  84.   {
  85.     no strict qw<refs>;
  86.  
  87.     if (@{"${pack}::EXPORT_OK"}) {
  88.       for my $func (@funcs) {
  89.         if (any{$_ eq $func} @{"${pack}::EXPORT_OK"}) {
  90.           *{"${c_pack}::${func}"} = \&{"${pack}::${func}"};
  91.         }else {
  92.           die "Can't find \"$func\" in the export list";
  93.         }
  94.       }
  95.     }
  96.   }
  97. }
  98.  
  99. 1; # End of MyExporter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement