Tag Archives: String

Legible Word Scrambling

I was recently reading the Lucky Basartd page on the Stone Brewery website and I remembered an (unverified) study claiming “scrambled words are legible as long as first and last letters are in place.” For grins, I whipped up a Python script to scramble a word/sentence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

Substrings in C

Sometimes I get frustrated about that things that aren’t included in the C standard libs. Chief among my frustrations: there is no substring function! I know C is bare-bones for a reason, but they couldn’t think to include it in <string.h>?

I also posed this question on Stack Overflow and there was quite a bit of good discussion about substrings in C: 
http://stackoverflow.com/questions/7406219/why-is-substring-not-part-of-the-c-standard-library

So, after a bit of researching I came up with this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

Perl tip – Reading a file into a string

I recently needed to check to see if a file had a particular tag in it before continuing, but I didn’t want to have to read it line by line to find out.

To my astonishment, there is no simple way to read a whole file into a string in Perl. The simple solution would be to use File::Slurp, but since the script will be running in a closed system I could only use default libraries. Also, because it’s Perl, I wanted to do it in a single line to maintain maximum incomprehensibility.

After a bit of tooling around I came up with this:

#!/usr/bin/perl -w

use strict;
use warnings;

# Check the file to ensure it contains the tag before continuing
my $FILE = $ARGV[0] or die $!;
die "File is missing required TIMESTAMP tag.n" unless do { local $/; local @ARGV = $FILE; <> } =~ /TIMESTAMP/;
...

More simply, here is the code to just stick the file contents in a variable:

my $contents = do { local $/; local @ARGV = $FILE; <> };

Essentially, what’s going on here is that I’m unsetting ‘$/’, the Input Record Separator, to make <> give the whole file at once.

Props to Stack Overflow for pointing me in the right direction.