How can I perform introspection in Perl? - perl

In the Perl OOP, how can I dump all methods / fields in this class and its parent class.
my ($self) = #_;
I saw a lot of constructors as above. Then, what is #_?
I have Java / OOP background. If your explanation can follow Java domain, it will be much easier for me to understand.

What is #_? See perldoc -v #_
perldoc perlobj
mjd has an interesting article on introspection in Perl.
In addition, How do I list available methods on a given object or package in Perl? answers part of your question.
My preferred answer to that question uses Class::Inspector:
#!/usr/bin/env perl
use strict; use warnings;
use Class::Inspector;
use HTML::TokeParser::Simple;
my $methods = Class::Inspector->methods(
'HTML::TokeParser::Simple', 'full', 'public'
);
print "Methods:\n";
print "$_\n" for #$methods;
print "Superclasses\n";
use Class::ISA;
print join(", ", Class::ISA::super_path('HTML::TokeParser::Simple')), "\n";

Data::Printer is a quick way to get a list of available methods in the current class:
#!/usr/bin/env perl
use strict;
use warnings;
use DateTime;
use Data::Printer;
p( DateTime->now );
This will print something like:
DateTime {
public methods (134) : add, add_duration, am_or_pm, bootstrap, ce_year, christian_era, clone, compare, compare_ignore_floating, date, datetime, day, day_abbr, day_name, day_of_month, day_of_month_0, day_of_quarter, day_of_quarter_0, day_of_week, day_of_week_0, day_of_year, day_of_year_0, day_0, DefaultLanguage, DefaultLocale, delta_days, delta_md, delta_ms, dmy, doq, doq_0, dow, dow_0, doy, doy_0, duration_class, epoch, era, era_abbr, era_name, format_cldr, formatter, fractional_second, from_day_of_year, from_epoch, from_object, hires_epoch, hms, hour, hour_1, hour_12, hour_12_0, INFINITY, is_dst, is_finite, is_infinite, is_leap_year, iso8601, jd, language, last_day_of_month, leap_seconds, local_day_of_week, local_rd_as_seconds, local_rd_values, locale, MAX_NANOSECONDS, mday, mday_0, mdy, microsecond, millisecond, min, minute, mjd, mon, mon_0, month, month_abbr, month_name, month_0, NAN, nanosecond, NEG_INFINITY, new, now, offset, quarter, quarter_abbr, quarter_name, quarter_0, sec, second, SECONDS_PER_DAY, secular_era, set, set_day, set_formatter, set_hour, set_locale, set_minute, set_month, set_nanosecond, set_second, set_time_zone, set_year, STORABLE_freeze, STORABLE_thaw, strftime, subtract, subtract_datetime, subtract_datetime_absolute, subtract_duration, time, time_zone, time_zone_long_name, time_zone_short_name, today, truncate, utc_rd_as_seconds, utc_rd_values, utc_year, wday, wday_0, week, week_number, week_of_month, week_year, weekday_of_month, year, year_with_christian_era, year_with_era, year_with_secular_era, ymd
private methods (38) : _accumulated_leap_seconds, _add_overload, _adjust_for_positive_difference, _calc_local_components, _calc_local_rd, _calc_utc_components, _calc_utc_rd, _cldr_pattern, _compare, _compare_overload, _day_has_leap_second, _day_length, _era_index, _format_nanosecs, _handle_offset_modifier, _is_leap_year, _month_length, _new, _new_from_self, _normalize_leap_seconds, _normalize_nanoseconds, _normalize_seconds, _normalize_tai_seconds, _offset_for_local_datetime, _rd2ymd, _seconds_as_components, _space_padded_string, _string_compare_overload, _string_equals_overload, _string_not_equals_overload, _stringify, _subtract_overload, _time_as_seconds, _utc_hms, _utc_ymd, _weeks_in_year, _ymd2rd, _zero_padded_number
internals: {
formatter undef,
local_c {
day 13,
day_of_quarter 13,
day_of_week 5,
day_of_year 104,
hour 15,
minute 5,
month 4,
quarter 2,
second 16,
year 2012
},
local_rd_days 734606,
local_rd_secs 54316,
locale DateTime::Locale::en_US,
offset_modifier 0,
rd_nanosecs 0,
tz DateTime::TimeZone::UTC,
utc_rd_days 734606,
utc_rd_secs 54316,
utc_year 2013
}
}

Related

Gnuplot prints a strange year, 30 years later

I have the next problem with gnuplot, when I print the time gnuplot
prints de time+30years.
This is a part of my data:
1411336800,1390,0,0,0,10,1411,0,10,0,0,0,0,0,1411
1411340400,1506,0,0,0,10,969,0,10,0,0,0,0,0,969
1411344000,1115,0,0,0,10,1108,0,10,0,0,0,0,0,1108
1411347600,719,0,0,0,10,712,0,10,0,0,0,0,0,712
A part of the script is:
set timefmt "%s"
stats "<tail -1 uur.txt " using 1:2 nooutput
tijd = strftime("%d %B %Y %H:%M", STATS_max_x)
print tijd
And then gnuplot prints: 21 September 2044 01:00. 44 ?
Has some one a clue?
I tried several formats but nothing helped.
Until version 4.6, internally gnuplot uses the 1. January 2000 as reference for its date and time functions (in version 5.0 the standard Unix timestamp is used).
You shouldn't have any problems with set timefmt "%s" if you plot the data. But when using strftime it makes a difference. Since you're using tail anyway, you can simply use
tijd = system('date -d #$(tail -1 uur.txt | cut -d, -f1) +"%d %B %Y %H:%M"')
print tijd

A better chi-square test for Perl?

Let's say I roll a 6-sided die 60 times and I get 16, 5, 9, 7, 6, 15 roles for the numbers 1 through 6, respectively. The numbers 1 and 6 are showing up too much and there's only about a 1.8% chance of that being random. If I use Statistics::ChiSquare, it prints out:
There's a >1% chance, and a <5% chance, that this data is random.
So not only is it a bad interface (I can't get those numbers back directly), but the rounding error is significant.
What's worse, what if I'm rolling 2 six sided dice? The odds of getting any particular number are:
Sum Frequency Relative Frequency
2 1 1/36
3 2 2/36
4 3 3/36
5 4 4/36
6 5 5/36
7 6 6/36
8 5 5/36
9 4 4/36
10 3 3/36
11 2 2/36
12 1 1/36
Statistics::ChiSquare used to have a chisquare_nonuniform() function, but it was removed.
So the numbers are rounded poorly and I can't use it for a non-uniform distribution. Given a list of actual frequency and a list of expected frequency, what's the best way of calculating the chi-square test in Perl? The various modules I'm finding on the CPAN aren't helping me, so I'm guessing I missed something obvious.
Implementing this yourself is so simple that I wouldn't want to upload Yet Another Statistics Module just for this.
use Carp qw< croak >;
use List::Util qw< sum >;
use Statistics::Distributions qw< chisqrprob >;
sub chi_squared_test {
my %args = #_;
my $observed = delete $args{observed} // croak q(Argument "observed" required);
my $expected = delete $args{expected} // croak q(Argument "expected" required);
#$observed == #$expected or croak q(Input arrays must have same length);
my $chi_squared = sum map {
($observed->[$_] - $expected->[$_])**2 / $expected->[$_];
} 0 .. $#$observed;
my $degrees_of_freedom = #$observed - 1;
my $probability = chisqrprob($degrees_of_freedom, $chi_squared);
return $probability;
}
say chi_squared_test
observed => [16, 5, 9, 7, 6, 17],
expected => [(10) x 6];
Output: 0.018360

Perl Tk::Date - toggle by week

I am in the process of writing a GUI which will monitor if various measurements have been made on a weekly basis. I have written various other GUIs for updating measurements results each day onto a database. These GUIs use Tk::Date datewidget that allows me to toggle by days
my $datewidget = $f_filter->Date(-choices=>'today', -datefmt=>'%2d %2m %4y',
-fields=>'date', -varfmt=>'datehash',
-monthmenu=>1, -allarrows=>1,
-value=>'now', -command=>\&populate)->pack(-side=>'left');
This lets me use the up and down arrows to increment/decrement days, change months and year.
What I desire to do in the weekly GUI is have an up and down arrow that will toggle by week only. Eg this week would be 'Mon Nov 4 - Fri Nov 8', next week 'Mon Nov 11 to Fri Nov 15'
I would like to be able to go forwards and backwards several years.
Is there a simple way to do this in perl-Tk::Date or Date::Entry?
Tk::Date and Tk::DateEntry cannot do this out of the box. With Tk::Date, I can propose the following approach:
use -varfmt => 'unixtime' instead of datehash, because the latter does not work well with the ->configure(-value => ...) call used later
set -editable=>0 to remove all arrow buttons created by Tk::Date
create the inc/dec buttons yourself
and make the date calculations using DateTime (see the incweek subroutine here)
Something like the following could work:
use strict;
use Tk;
use Tk::Date;
my $mw = tkinit;
my $datewidget = $mw->Date(-choices=>'today', -datefmt=>'%2d %2m %4y',
-fields=>'date', -varfmt=>'unixtime',
-editable=>0,
-monthmenu=>1,
-value=>'now',
-command=>sub { warn "populate #_" })->pack(-side=>'left');
my $arrowframe = $mw->Frame->pack(-side => 'left');
{
no warnings 'once'; # because of INCBITMAP/DECBITMAP
$arrowframe->FireButton(-bitmap => $Tk::FireButton::INCBITMAP, -command => sub { incweek(+1) })->pack(-side => 'top');
$arrowframe->FireButton(-bitmap => $Tk::FireButton::DECBITMAP, -command => sub { incweek(-1) })->pack(-side => 'top');
}
MainLoop;
sub incweek {
my($inc) = #_;
use DateTime;
my $epoch = $datewidget->get;
my $dt = DateTime->from_epoch(epoch => $epoch);
$dt = $dt->add(weeks => $inc);
$datewidget->configure(-value => $dt->epoch);
}
__END__
Note that $datewidget->get returrns now the epoch time, but using DateTime you can easily convert this into y/m/d values.

How do I set the cookie expiration for MojoX::Sessions?

Whatever expiration value that I give to expires() or expires_delta(), the cookie expiration is always one hour. How do I change it so that the session and the cookie expiration times match?
Although I like vti's work, that distribution looks outdated and was replaced in the past. Today the standard way to set session expire dates is explained in Mojolicious::Sessions:
default_expiration
my $time = $sessions->default_expiration;
$sessions = $sessions->default_expiration(3600);
Default time for sessions to expire in seconds from now, defaults to
3600. The expiration timeout gets refreshed for every request. Setting the value to 0 will allow sessions to persist until the browser window
is closed, this can have security implications though. For more
control you can also use the expiration and expires session values.
# Expiration date in epoch seconds from now (persists between requests)
$c->session(expiration => 604800);
# Expiration date as absolute epoch time (only valid for one request)
$c->session(expires => time + 604800);
# Delete whole session by setting an expiration date in the past
$c->session(expires => 1);
I wrote a small test script to make sure it works:
#!/usr/bin/env perl
use Mojolicious::Lite;
use Time::Local 'timegm';
# set some session variable
get '/test' => sub {
my $self = shift;
$self->session(
expires => timegm(0, 0, 0, 4, 4, 142), # star wars day '42
foo => 42,
);
$self->render_text('foo is set');
};
use Test::More;
use Test::Mojo;
use Mojo::Cookie::Response;
my $t = Test::Mojo->new;
$t->get_ok('/test')->status_is(200)->content_is('foo is set');
my $cookies = Mojo::Cookie::Response->parse($t->tx->res->headers->set_cookie);
is $cookies->[0]->expires, 'Sun, 04 May 2042 00:00:00 GMT', 'right expire time';
done_testing;
Output:
ok 1 - get /test
ok 2 - 200 OK
ok 3 - exact match for content
ok 4 - right expire time
1..4

How do I elegantly print the date in RFC822 format in Perl?

How can I elegantly print the date in RFC822 format in Perl?
use POSIX qw(strftime);
print strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())) . "\n";
The DateTime suite gives you a number of different ways, e.g.:
use DateTime;
print DateTime->now()->strftime("%a, %d %b %Y %H:%M:%S %z");
use DateTime::Format::Mail;
print DateTime::Format::Mail->format_datetime( DateTime->now() );
print DateTime->now( formatter => DateTime::Format::Mail->new() );
Update: to give time for some particular timezone, add a time_zone argument
to now():
DateTime->now( time_zone => $ENV{'TZ'}, ... )
It can be done with strftime, but its %a (day) and %b (month) are expressed in the language of the current locale.
From man strftime:
%a The abbreviated weekday name according to the current locale.
%b The abbreviated month name according to the current locale.
The Date field in mail must use only these names (from rfc2822 DATE AND TIME SPECIFICATION):
day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun"
month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
"Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
Therefore portable code should switch to the C locale:
use POSIX qw(strftime locale_h);
my $old_locale = setlocale(LC_TIME, "C");
my $date_rfc822 = strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time()));
setlocale(LC_TIME, $old_locale);
print "$date_rfc822\n";
Just using POSIX::strftime() has issues that have already been pointed out in other answers and comments on them:
It will not work with MS-DOS aka Windows which produces strings like "W. Europe Standard Time" instead of "+0200" as required by RFC822 for the %z conversion specification.
It will print the abbreviated month and day names in the current locale instead of English, again required by RFC822.
Switching the locale to "POSIX" resp. "C" fixes the latter problem but is potentially expensive, even more for well-behaving code that later switches back to the previous locale.
But it's also not completely thread-safe. While temporarily switching locale will work without issues inside Perl interpreter threads, there are races when the Perl interpreter itself runs inside a kernel thread. This can be the case, when the Perl interpreter is embedded into a server (for example mod_perl running in a threaded Apache MPM).
The following version doesn't suffer from any such limitations because it doesn't use any locale dependent functions:
sub rfc822_local {
my ($epoch) = #_;
my #time = localtime $epoch;
use integer;
my $tz_offset = (Time::Local::timegm(#time) - $now) / 60;
my $tz = sprintf('%s%02u%02u',
$tz_offset < 0 ? '-' : '+',
$tz_offset / 60, $tz_offset % 60);
my #month_names = qw(Jan Feb Mar Apr May Jun
Jul Aug Sep Oct Nov Dec);
my #day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
return sprintf('%s, %02u %s %04u %02u:%02u:%02u %s',
$day_names[$time[6]], $time[3], $month_names[$time[4]],
$time[5] + 1900, $time[2], $time[1], $time[0], $tz);
}
But it should be noted that converting from seconds since the epoch to a broken down time and vice versa are quite complex and expensive operations, even more when not dealing with GMT/UTC but local time. The latter requires the inspection of zoneinfo data that contains the current and historical DST and time zone settings for the current time zone. It's also error-prone because these parameters are subject to political decisions that may be reverted in the future. Because of that, code relying on the zoneinfo data is brittle and may break, when the system is not regulary updated.
However, the purpose of RFC822 compliant date and time specifications is not to inform other servers about the timezone settings of "your" server but to give its notion of the current date and time in a timezone indepent manner. You can save a lot of CPU cycles (they can be measured in CO2 emission) on both the sending and receiving end by simply using UTC instead of localtime:
sub rfc822_gm {
my ($epoch) = #_;
my #time = gmtime $epoch;
my #month_names = qw(Jan Feb Mar Apr May Jun
Jul Aug Sep Oct Nov Dec);
my #day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
return sprintf('%s, %02u %s %04u %02u:%02u:%02u +0000',
$day_names[$time[6]], $time[3], $month_names[$time[4]],
$time[5] + 1900, $time[2], $time[1], $time[0]);
}
By hard-coding the timezone to +0000 you avoid all of the above mentioned problems, while still being perfectly standards compliant, leave alone faster. Go with that solution, when performance could be an issue for you. Go with the first solution, when your users complain about the software reporting the "wrong" timezone.