Found in /usr/share/perl/5.34/pod/perlfaq3.pod How do I find which modules are installed on my system? From the command line, you can use the "cpan" command's "-l" switch: $ cpan -l You can also use "cpan"'s "-a" switch to create an autobundle file that "CPAN.pm" understands and can use to re-install every module: $ cpan -a Inside a Perl program, you can use the ExtUtils::Installed module to show all installed distributions, although it can take awhile to do its magic. The standard library which comes with Perl just shows up as "Perl" (although you can get those with Module::CoreList). use ExtUtils::Installed; my $inst = ExtUtils::Installed->new(); my @modules = $inst->modules(); If you want a list of all of the Perl module filenames, you can use File::Find::Rule: use File::Find::Rule; my @files = File::Find::Rule-> extras({follow => 1})-> file()-> name( '*.pm' )-> in( @INC ) ; If you do not have that module, you can do the same thing with File::Find which is part of the standard library: use File::Find; my @files; find( { wanted => sub { push @files, $File::Find::fullname if -f $File::Find::fullname && /\.pm$/ }, follow => 1, follow_skip => 2, }, @INC ); print join "\n", @files; If you simply need to check quickly to see if a module is available, you can check for its documentation. If you can read the documentation the module is most likely installed. If you cannot read the documentation, the module might not have any (in rare cases): $ perldoc Module::Name You can also try to include the module in a one-liner to see if perl finds it: $ perl -MModule::Name -e1 (If you don't receive a "Can't locate ... in @INC" error message, then Perl found the module name you asked for.) Found in /usr/share/perl/5.34/pod/perlfaq4.pod How do I find the day or week of the year? The day of the year is in the list returned by the "localtime" function. Without an argument "localtime" uses the current time. my $day_of_year = (localtime)[7]; The POSIX module can also format a date as the day of the year or week of the year. use POSIX qw/strftime/; my $day_of_year = strftime "%j", localtime; my $week_of_year = strftime "%W", localtime; To get the day of year for any date, use POSIX's "mktime" to get a time in epoch seconds for the argument to "localtime". use POSIX qw/mktime strftime/; my $week_of_year = strftime "%W", localtime( mktime( 0, 0, 0, 18, 11, 87 ) ); You can also use Time::Piece, which comes with Perl and provides a "localtime" that returns an object: use Time::Piece; my $day_of_year = localtime->yday; my $week_of_year = localtime->week; The Date::Calc module provides two functions to calculate these, too: use Date::Calc; my $day_of_year = Day_of_Year( 1987, 12, 18 ); my $week_of_year = Week_of_Year( 1987, 12, 18 ); How do I find the current century or millennium? Use the following simple functions: sub get_century { return int((((localtime(shift || time))[5] + 1999))/100); } sub get_millennium { return 1+int((((localtime(shift || time))[5] + 1899))/1000); } On some systems, the POSIX module's "strftime()" function has been extended in a non-standard way to use a %C format, which they sometimes claim is the "century". It isn't, because on most such systems, this is only the first two digits of the four-digit year, and thus cannot be used to determine reliably the current century or millennium. How can I compare two dates and find the difference? (contributed by brian d foy) You could just store all your dates as a number and then subtract. Life isn't always that simple though. The Time::Piece module, which comes with Perl, replaces localtime with a version that returns an object. It also overloads the comparison operators so you can compare them directly: use Time::Piece; my $date1 = localtime( $some_time ); my $date2 = localtime( $some_other_time ); if( $date1 < $date2 ) { print "The date was in the past\n"; } You can also get differences with a subtraction, which returns a Time::Seconds object: my $date_diff = $date1 - $date2; print "The difference is ", $date_diff->days, " days\n"; If you want to work with formatted dates, the Date::Manip, Date::Calc, or DateTime modules can help you. How can I find the Julian Day? (contributed by brian d foy and Dave Cross) You can use the Time::Piece module, part of the Standard Library, which can convert a date/time to a Julian Day: $ perl -MTime::Piece -le 'print localtime->julian_day' 2455607.7959375 Or the modified Julian Day: $ perl -MTime::Piece -le 'print localtime->mjd' 55607.2961226851 Or even the day of the year (which is what some people think of as a Julian day): $ perl -MTime::Piece -le 'print localtime->yday' 45 You can also do the same things with the DateTime module: $ perl -MDateTime -le'print DateTime->today->jd' 2453401.5 $ perl -MDateTime -le'print DateTime->today->mjd' 53401 $ perl -MDateTime -le'print DateTime->today->doy' 31 You can use the Time::JulianDay module available on CPAN. Ensure that you really want to find a Julian day, though, as many people have different ideas about Julian days (see <http://www.hermetic.ch/cal_stud/jdn.htm> for instance): $ perl -MTime::JulianDay -le 'print local_julian_day( time )' 55608 How do I find yesterday's date? (contributed by brian d foy) To do it correctly, you can use one of the "Date" modules since they work with calendars instead of times. The DateTime module makes it simple, and give you the same time of day, only the day before, despite daylight saving time changes: use DateTime; my $yesterday = DateTime->now->subtract( days => 1 ); print "Yesterday was $yesterday\n"; You can also use the Date::Calc module using its "Today_and_Now" function. use Date::Calc qw( Today_and_Now Add_Delta_DHMS ); my @date_time = Add_Delta_DHMS( Today_and_Now(), -1, 0, 0, 0 ); print "@date_time\n"; Most people try to use the time rather than the calendar to figure out dates, but that assumes that days are twenty-four hours each. For most people, there are two days a year when they aren't: the switch to and from summer time throws this off. For example, the rest of the suggestions will be wrong sometimes: Starting with Perl 5.10, Time::Piece and Time::Seconds are part of the standard distribution, so you might think that you could do something like this: use Time::Piece; use Time::Seconds; my $yesterday = localtime() - ONE_DAY; # WRONG print "Yesterday was $yesterday\n"; The Time::Piece module exports a new "localtime" that returns an object, and Time::Seconds exports the "ONE_DAY" constant that is a set number of seconds. This means that it always gives the time 24 hours ago, which is not always yesterday. This can cause problems around the end of daylight saving time when there's one day that is 25 hours long. You have the same problem with Time::Local, which will give the wrong answer for those same special cases: # contributed by Gunnar Hjalmarsson use Time::Local; my $today = timelocal 0, 0, 12, ( localtime )[3..5]; my ($d, $m, $y) = ( localtime $today-86400 )[3..5]; # WRONG printf "Yesterday: %d-%02d-%02d\n", $y+1900, $m+1, $d; How do I find matching/nesting anything? To find something between two single characters, a pattern like "/x([^x]*)x/" will get the intervening bits in $1. For multiple ones, then something more like "/alpha(.*?)omega/" would be needed. For nested patterns and/or balanced expressions, see the so-called (?PARNO) construct (available since perl 5.10). The CPAN module Regexp::Common can help to build such regular expressions (see in particular Regexp::Common::balanced and Regexp::Common::delimited). More complex cases will require to write a parser, probably using a parsing module from CPAN, like Regexp::Grammars, Parse::RecDescent, Parse::Yapp, Text::Balanced, or Marpa::R2. How do I find the soundex value of a string? (contributed by brian d foy) You can use the "Text::Soundex" module. If you want to do fuzzy or close matching, you might also try the String::Approx, and Text::Metaphone, and Text::DoubleMetaphone modules. How do I find the first array element for which a condition is true? To find the first array element which satisfies a condition, you can use the "first()" function in the List::Util module, which comes with Perl 5.8. This example finds the first element that contains "Perl". use List::Util qw(first); my $element = first { /Perl/ } @array; If you cannot use List::Util, you can make your own loop to do the same thing. Once you find the element, you stop the loop with last. my $found; foreach ( @array ) { if( /Perl/ ) { $found = $_; last } } If you want the array index, use the "firstidx()" function from "List::MoreUtils": use List::MoreUtils qw(firstidx); my $index = firstidx { /Perl/ } @array; Or write it yourself, iterating through the indices and checking the array element at each index until you find one that satisfies the condition: my( $found, $index ) = ( undef, -1 ); for( $i = 0; $i < @array; $i++ ) { if( $array[$i] =~ /Perl/ ) { $found = $array[$i]; $index = $i; last; } } Found in /usr/share/perl/5.34/pod/perlfaq7.pod How can I find out my current or calling package? (contributed by brian d foy) To find the package you are currently in, use the special literal "__PACKAGE__", as documented in perldata. You can only use the special literals as separate tokens, so you can't interpolate them into strings like you can with variables: my $current_package = __PACKAGE__; print "I am in package $current_package\n"; If you want to find the package calling your code, perhaps to give better diagnostics as Carp does, use the "caller" built-in: sub foo { my @args = ...; my( $package, $filename, $line ) = caller; print "I was called from package $package\n"; ); By default, your program starts in package "main", so you will always be in some package. This is different from finding out the package an object is blessed into, which might not be the current package. For that, use "blessed" from Scalar::Util, part of the Standard Library since Perl 5.8: use Scalar::Util qw(blessed); my $object_package = blessed( $object ); Most of the time, you shouldn't care what package an object is blessed into, however, as long as it claims to inherit from that class: my $is_right_class = eval { $object->isa( $package ) }; # true or false And, with Perl 5.10 and later, you don't have to check for an inheritance to see if the object can handle a role. For that, you can use "DOES", which comes from "UNIVERSAL": my $class_does_it = eval { $object->DOES( $role ) }; # true or false You can safely replace "isa" with "DOES" (although the converse is not true). Found in /usr/share/perl/5.34/pod/perlfaq8.pod How do I find out which operating system I'm running under? The $^O variable ($OSNAME if you use "English") contains an indication of the name of the operating system (not its release number) that your perl binary was built for. How do I find out if I'm running interactively or not? (contributed by brian d foy) This is a difficult question to answer, and the best answer is only a guess. What do you really want to know? If you merely want to know if one of your filehandles is connected to a terminal, you can try the "-t" file test: if( -t STDOUT ) { print "I'm connected to a terminal!\n"; } However, you might be out of luck if you expect that means there is a real person on the other side. With the Expect module, another program can pretend to be a person. The program might even come close to passing the Turing test. The IO::Interactive module does the best it can to give you an answer. Its "is_interactive" function returns an output filehandle; that filehandle points to standard output if the module thinks the session is interactive. Otherwise, the filehandle is a null handle that simply discards the output: use IO::Interactive; print { is_interactive } "I might go to standard output!\n"; This still doesn't guarantee that a real person is answering your prompts or reading your output. If you want to know how to handle automated testing for your distribution, you can check the environment. The CPAN Testers, for instance, set the value of "AUTOMATED_TESTING": unless( $ENV{AUTOMATED_TESTING} ) { print "Hello interactive tester!\n"; } Found in /usr/share/perl/5.34/pod/perlfaq9.pod How do I find the user's mail address? Ask them for it. There are so many email providers available that it's unlikely the local system has any idea how to determine a user's email address. The exception is for organization-specific email (e.g. foo AT yourcompany.com) where policy can be codified in your program. In that case, you could look at $ENV{USER}, $ENV{LOGNAME}, and getpwuid($<) in scalar context, like so: my $user_name = getpwuid($<) But you still cannot make assumptions about whether this is correct, unless your policy says it is. You really are best off asking the user. How do I find out my hostname, domainname, or IP address? (contributed by brian d foy) The Net::Domain module, which is part of the Standard Library starting in Perl 5.7.3, can get you the fully qualified domain name (FQDN), the host name, or the domain name. use Net::Domain qw(hostname hostfqdn hostdomain); my $host = hostfqdn(); The Sys::Hostname module, part of the Standard Library, can also get the hostname: use Sys::Hostname; $host = hostname(); The Sys::Hostname::Long module takes a different approach and tries harder to return the fully qualified hostname: use Sys::Hostname::Long 'hostname_long'; my $hostname = hostname_long(); To get the IP address, you can use the "gethostbyname" built-in function to turn the name into a number. To turn that number into the dotted octet form (a.b.c.d) that most people expect, use the "inet_ntoa" function from the Socket module, which also comes with perl. use Socket; my $address = inet_ntoa( scalar gethostbyname( $host || 'localhost' ) );
Generated by phpman v3.7.12 Author: Che Dong Under GNU General Public License
2026-06-13 17:16 @216.73.216.233
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)