Showing entries with tag "Perl".

Found 24 entries

Perl: regular expression to check for ANSI sequences
I needed to test if a given string contains ANSI color codes. Here is the regexp I settled on to check for that: ```perl my $ansi_color_regex = qr/\e\[[0-9]{1,3}(?:;[0-9]{1,3}){0,3}[mK]/; if ($str =~ /$ansi_color_regex/) { print "String has some ANSI in it\n"; } ``` Alternately you can *capture* the color numbers with this regex: ```perl my...
Perl: Natural Sort
I have a array with a bunch of names like `vlan-1`, `vlan100`, `vlan34` which do not sort appropriately using Perl's standard `sort()` function. [Sort::Naturally](https://github.com/bingos/sort-naturally/) to the rescue! I didn't want to install an entire module for one sort operation, and require a dependency, so I ripped out just the natural sort function and...
Perl: Working with columnar data
I have a text file of data that is in whitespace separated columns that I need to work with. Perl has a command line option `-a` to enable auto-splitting the input into an array called `@F`. Using a Perl one-liner you can automatically split at whitespace separation like this: ``` cat /tmp/file_list.txt | perl -lane 'print "mv $F[3] $F[1]"' ``` This will output `mv` commands to rename the file in the 4th column to the 2nd column. More...
PHP: Quote Word
I needed a function similar to Perl's [qw](http://perlmeme.org/howtos/perlfunc/qw_function.html). If you pass a string to this function it will return an array of the words, stripping any separating whitespace. If you pass true as the second parameter you will instead get a hash returning each word in a key/value pair. ...
Perl: remove empty elements from array
I have an array with a bunch of empty strings, and other "empty" items, that I want to remove. Perl's [grep()](http://perldoc.perl.org/functions/grep.html) command makes this very simple: ```perl @a = ("one", "", "three", "four", 0, "", undef, "eight"); @b = grep($_, @a); # @b = ("one","three","four","eight"); ``` The first argument to grep is an expression which evaluates whether `$_` is a truthy value. This could easily also...
Perl: assign a regexp search/replace to a variable
...not what we wanted. Instead we want the search and replace to *return* the new string: ``` $str = "foofoofoobar"; $new = $str =~ s/foo/FOO/gr; print "$new\n"; ``` Note the `/r` after the regular expression. Documentation on `/r` is in [Perlop](http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators)
Perl: Using modules and @INC
I was going to write an article about using modules in Perl but [Perl Maven](http://perlmaven.com/how-to-change-inc-to-find-perl-modules-in-non-standard-locations) did a better job than I ever could have. The article explains all the places Perl looks to find a given module, and how you give it alternate locations. The only thing I would add is that if you print out `%INC` it will list all the modules that were loaded, and from where. ``` use Data::Dumper; print Dumper(\%INC); ``` ...
Perl: ANSI colors
Perl's `Term::ANSIColor` is good but sometime it's overkill. I wrote a function to change colors before your print. ```perl $color = color("13_on_5"); $reset = color("reset"); print $color . "Pink on purple" . $reset . "\n"; ``` ```perl # String format: '115', '165bold', '10_on_140', 'reset', 'on_173' sub color { my $str = shift(); # If we're NOT connected to a an interactive terminal don't do color if (-t STDOUT == 0) { return ''; } # No string sent in, so we just...
Perl: Quick extract variables from @ARGV
I'm a big fan of [Getopt::Long](http://perldoc.perl.org/Getopt/Long.html), but sometimes I do not want to include a large module to extract two arguments. I wrote a quick function that will parse **simple** command line arguments and give you a hash of their values. ```perl sub argv { my $ret...
Perl: See the path of a module
I've been testing various version of a Perl module and I wanted to make sure I was testing with the right one. This code snippet will output the paths of the loaded modules. ~~~ perl -MData::Dump::Color -e 'dd(\%INC);' ~~~ This example loads Data::Dump::Color and then outputs the contents of %INC which contains the paths of all loaded modules.
Perl: Count number of a specific character in a string
I needed to count how many * characters were in a string, so I wrote this simple function. ~~~perl sub char_count { my ($needle,$str) = @_; my $len = length($str); my $ret = 0; for (my $i = 0; $i < $len; $i++) { my $found = substr($str,$i,1); if ($needle eq $found) { $ret++; } } return $ret; } ~~~ You can also write...
Perl: find the index of an array item
I needed to find the index of an item in an array so I wrote a simple Perl function. sub array_id { my ($needle,@haystack) = @_; my $count = 0; foreach my $item (@haystack) { if ($item eq $needle) { return $count; } $count++; ...
Perl: Conditionally load a module
I am using **Data::Dump** which has a drop in replacement named **Data::Dump::Color**. I wanted to conditionally/programmatically load a specific module. if ($color) { use Data::Dump::Color; } else { use Data::Dump; } This doesn't work because use statements are run before ANY other code is run. The above code will load BOTH modules, because **use** always runs. Instead you have to use **require**. if ($color) { require Data::Dump::Color; Data::Dump::Color->import(); } else { require Data::Dump; Data::Dump->import(); } Calling require does **not** automatically import all the exported functions, so you have to specifically call the include() function.
Perl: Increment a number in a text file
I have a manifest file that contains a build_version=XX number field (among a lot of others) that I want to automatically increment. Here is a simple Perl one-liner to increment that number in a given file. ~~~ perl -pi -e 's/(build_version)=(\d+)/"build_version=" . ($2 + 1)/e' manifest ~~~ In this example the `/e` in the regexp says that the replace value is an [expression](http://perldoc.perl.org/perlop.html). In this case the replace value is some math...
Perl: detect if a module is installed before using it
I wanted to check if a Perl module was installed at runtime, and error out accordingly if it wasn't. This allows me to print intelligent error messages if a module is not installed. ```perl eval { require Weird::Module; }; if ($@) { die("Module is not installed\n"); } ``` This allows you to create runtime functions depending on which module is installed: ``` # Debug print variable using either Data::Dump::Color (preferred)...
Perl: doing a regexp replace on an array
I have an array of items that I want to do a quick regexp replace on each element. Here is a very elegant solution: @names = ("John", "Paul", "george", "Ringo"); s/^g/G/g for @names; print join(", ",@names);
Perl: Count occurrences of substring
I needed a quick way to count the number of times a substring appears in a larger string. $count = @{[$haystack =~ /$needle/g]}; Updated: This is a more clear solution: my $count = scalar(split(/$needle/,$haystack)) - 1; Lots of good options found in the comments though.
Perlfunc: human_size()
Quicky function to get data size in human readable format. ```perl sub human_size { my $size = shift(); if ($size > 1024**3) { $size = sprintf("%.1fG",$size / 1024**3); } elsif ($size > 1024**2) { $size = sprintf("%.1fM",$size / 1024**2); } elsif ($size > 1024) { $size =...
Perl: END { }
Sometimes in coding I've found that you need to have code that runs on exit, regardless of why. In Python you can use [`atexit`](https://docs.python.org/3.3/library/atexit.html) but in Perl it's as easy as defining an `END` code block: ```perl END { # Do some clean up code close OUTPUT_FILE; output_close_message() } ``` Cool it looks like there is a [`BEGIN`](http://perldoc.perl.org/perlmod.html#BEGIN%2c-UNITCHECK%2c-CHECK%2c-INIT-and-END) method as well!
Perlfunc: days_in_month
Code to figure out the days in a given month. Of course it's leap year aware. ``` sub days_in_month() { use Time::Local; my ($month,$year) = @_; if ($month < 1 || $month > 31) { return 0; } if ($year < 1970 || $year > 2036) { return 0; } my $secs = timelocal(0,0,13,1,$month - 1,$year); for (my $i = 27; $i < 32; $i++) { my $new_month = ((localtime($secs + ($i * 86400)))[4]) + 1; if ($new_month != $month) { return $i; } } } ```
Perl: Seconds Since Midnight
Some quick perl to return the number of seconds in the current day since midnight. ``` sub midnight_seconds { my @time = localtime(); my $secs = ($time[2] * 3600) + ($time[1] * 60) + $time[0]; return $secs; } ``` The same code just written...
Perl Sexy Data Structure
Just an example of a weird/exotic/sexy data structure in Perl. This is correct syntax, just in case I need to reference it in the future. ``` %hash = ( 1 => 'one', 2 => 'two', 3 => { 'blind' => 'mice', 'musketeers' => 'men', }, 4 => 'four', 5 => { 'spanish' => 'cinco', 'french'...
Perl: Sorting a hash
This syntax still doesn't make much sense to me but here is how you sort a perl hash by value. This returns a list of all the keys of the hash sorted in the order you want. To reverse the sort simply change $a and $b locations with each other. ``` @sort = sort{ $unique{$a} $unique{$b} } keys %unique; ```
Perl: Replace text in a file
If you need to replace some instances of a string in a file with something new you can use the following Perl one liner. ``` perl -pi -e "s/search/replace/g" /tmp/foo.txt ```