Sort By Part Of Filename

Jan 12
2008

Assume that we have directory, containing files like:

part_1.txt
part_2.txt
part_100.txt
part_200.txt

In case that we are interested in /(\d+)\.\w+$/ as part of the sorting criteria:

Perl

# short but unefficient
@a = sort {($a =~ /(\d+)\.\w+$/)[0] < => ($b =~  /(\d+)\.\w+$/)[0]} < *>;

Ruby

regex = Regexp.new(/(\d+)\.\w+$/)
 
# enum.sort {| a, b | block } => array
Dir["*"].grep(regex).sort do |a, b|
  a.match(regex)[0].to_i < => b.match(regex)[0].to_i
end
 
# enum.sort_by {| obj | block } => array
Dir["*"].grep(regex).sort_by do |name|
  name.match(regex)[1].to_i
end

Dynamically Define Methods

Jan 11
2008

Perl

package MyClass;
package main;
 
*MyClass::from_my_class = sub {
   print "defined in ", __PACKAGE__, "\n"
};
 
MyClass::from_my_class();

Ruby

class String
  def self.from_string
    print "defined in " + self.name + $/
  end
end
 
String::from_string
String. from_string

perldoc usage

Jan 09
2008

function manual:

perldoc -f grep

search the text in perlfaq:

perldoc -q grep

module content:

perldoc -m IO::Socket

module absolute filename:

perldoc -l IO::Socket

and of course:

perldoc perl

Just_Another_Perl_Hacker.pm

Jan 08
2008
package Just_Another_Perl_Hacker; $$
perl -MJust_Another_Perl_Hacker -e 's|(?< =\w)_| |g && tr/:://d && print for keys %main::'

Getting ip addresses from log file

Jan 08
2008
perl -ne '$_{$1}=1 if /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;eof&&{print join("\n", sort keys %_)}' access.log

Fast ICMP scanner (Perl oneliner)

Jan 08
2008

[localhost]$

time perl -MNet::Ping -e '$p = Net::Ping->new();
@hosts = qw(
127.0.0.1
172.16.0.1
172.16.0.2
172.16.0.5
172.16.0.254);
#the significant detail
$p->{"timeout"} = 0.005;
for (@hosts) { print "$_ is ".($p->ping($_) ? "up" : "down").$/ }'

127.0.0.1 is up
172.16.0.1 is up
172.16.0.2 is down
172.16.0.5 is up
172.16.0.254 is down

real 0m0.062s
user 0m0.040s
sys 0m0.000s

nmap cleaner in Perl

Dec 29
2007
$”=@ARGV;/^\D+/||print for`nmap$”`

Lists and Values

Nov 30
2007

Perl

($a, $b) = (1, 2);
@arr    = (1, 2);

Python

 a, b = 1, 2
arr = 1, 
arr = 1,2

Ruby

 a, b = 1, 2
arr  = 1, 2
arr  = 1,2, *[11,22] # the same as
arr  = [1,2, [11,22]].flatten

JAPH

Jul 19
2007
$_->[/^(?>(.)?(.)+.*)(?!\1)(??{print(($1..$2)[9,0,15,7])})/]

Fibonacci numbers in Ruby and Perl

Jul 19
2007

#!/usr/bin/env ruby

x=1;loop{p$.+=x=$.-x}

. #!/usr/bin/env perl

print$}+=$.=$}-$.||1while.1

Calendar

July 2010
M T W T F S S
« Apr    
 1234
567891011
12131415161718
19202122232425
262728293031  

Tags