Table of Contents
Convert AD LDAP date to Normal
RegEx Stuff
# Tokenize a string # matches: # field=value # field>value # field!=value # field~value my ($field, $op, $value) = $string =~ /(.*)(!=|>|<|~)(.*)/;
Getting KeyCodes
#!/usr/bin/perl -w use Term::ReadKey; ReadMode('cbreak'); print "Press keys to see their ASCII values. Use Ctrl-C to quit .\n"; print " Ctrl-C code is 3d, 3h, 3o btw\n"; while (1) { $char = ReadKey(0); last unless defined $char; printf(" Decimal: %d\tHex: %x\tOct: %o\n", ord($char), ord($char), ord($char)); } ReadMode('normal');
Sorting Array of HashMaps
my @data; push @data, { name => "Item A", price => 9.99 }; push @data, { name => "Item B", price => 4.99 }; push @data, { name => "Item C", price => 7.5};
We now have an array with 3 hashes in. Suppose we want to sort by price, how do we do it?
my @sorted = sort { $a->{price} <=> $b->{price} } @data;
Perl’s built in sort function allows us to specify a custom sort order. Within the curly braces Perl gives us 2 variables, $a and $b, which reference 2 items to compare. In our case, these are hash references so we can access the elements of the hash and sort by any key we want. A description of the ⇔ operator can be found on Perlfect. Suppose we want to sort in reverse order?
my @sorted = sort { $b->{price} <=> $a->{price} } @data;
Simple. You can test this by adding the following line to the bottom of the script.
print join "n", map {$_->{name}." - ".$_->{price}} @sorted;
Which gives us:
Item B - 4.99 Item C - 7.5 Item A - 9.99
Connecting to LDAP (AD)
#!/usr/bin/perl use warnings; use Net::LDAP; my $filter = $ARGV[0]; $ldap = Net::LDAP->new ( "letts.mcs.usyd.edu.au", port=>3268 ) or die "$@"; my $mesg = $ldap->bind ( "cn=pfowler,ou=extro,DC=mcs,DC=usyd,DC=edu,DC=au", password => "MyPass"); my $result = &LDAPsearch($ldap, "$filter"); &LDAPshow($result); $ldap->unbind(); exit 0; sub LDAPshow() { my ($result) = @_; my @entries = $result->entries; my $entr; foreach $entr ( @entries ) { my $attr; foreach $attr ( sort $entr->attributes ) { next if ( $attr =~ /;binary$/ ); print "$attr:", $entr->get_value ( $attr ) ,"\n"; } } } sub LDAPsearch() { my ($ldap,$searchString,$attrs,$base) = @_; if (!$base ) { $base = "ou=Users,dc=newioit,dc=com,DC=au"; } if (!$attrs ) { $attrs = [ 'distinguishedName','cn','sn','givenName','mail','streetAddress','postalCode','st','telephoneNumber','title','displayName' ]; } my $result = $ldap->search ( base=>"$base", scope=>"sub", filter=>"$searchString", attrs=>$attrs); #my $result = $ldap->search(filter=>"(cn=pfowler)", base=>$base, scope=>'sub'); return $result; }