Chapter 5:Perl One-Liners:Working with Arrays and Strings

weixin_34377065發表於2018-09-21

In this chapter, we’ll look at various one-liners for

  • creating strings and arrays,
  • for doing things like generating passwords,
  • creating strings of certain length,
  • finding the numeric values of characters,
  • creating arrays of numbers.

You’ll also learn about the range operator .., the x operator, the $, special variable, and the @ARGV array.

5.1 Generate and print the alphabet
    perl -le 'print a..z'

The $, is the field separator. It’s output by print between each field. Semantically, though, using join to separate the list of letters with a comma is more appealing because it works even when not using print directly:

    perl -le '$alphabet = join ",", ("a".."z"); print $alphabet'
5.2 Generate and print all the strings from “a” to “zz”
5.3 Create a hex lookup table
perl -le '
$num = 255;
@hex = (0..9, "a".."f");
while ($num) {
$s = $hex[($num % 16)].$s;
$num = int $num/16;
}
print $s
'

But surely, converting a number to hex is much easier if I use printf(or sprintf) with the %x format specifier.

    perl -le 'printf("%x", 255)'

To convert the number back from hex to dec, use the hex operator:

    perl -le '$num = "ff"; print hex $num'
5.4 Generate a random eight-character password
        perl -le 'print map { ("a".."z")[rand 26] } 1..8'
5.5 Create a string of specific length
    perl -le 'print "a"x50'

For example, if you need 1KB of data, just
do this:

    perl -e 'print "a"x1024'

When you use the repetition operator in the list context, with a list as its first operand, you create a list with the given elements repeated, like this:

    perl -le '@list = (1,2)x20; print "@list"'
5.6 Create an array from a string
    @months = split ' ', "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
5.7 Create a string from the command-line arguments
    perl -le 'print "(", (join ",", @ARGV), ")"' val1 val2 val3
5.8 Find the numeric values for characters in a string
    perl -le 'print join ", ", map { ord } split //, "hello world"'

You could also do this with the unpack operator by specifying C* as the unpacking template:

    perl -le 'print join ", ", unpack("C*", "hello world")'
5.9 Convert a list of numeric ASCII values into a string
perl -le '
@ascii = (99, 111, 100, 105, 110, 103);
print pack("C*", @ascii)
'

You can also use the @ARGV array and pass the ASCII values as arguments to the one-liner:

    perl -le 'print map chr, @ARGV' 99 111 100 105 110 103
5.10 Generate an array with odd numbers from 1 to 100
  perl -le '@odd = grep {$_ % 2 == 1} 1..100; print "@odd"'
5.11 Generate an array with even numbers from 1 to 100
      perl -le '@even = grep {$_ % 2 == 0} 1..100; print "@even"'
5.12 Find the length of a string
    perl -le 'print length "one-liners are great"'
5.13 Find the number of elements in an array
    perl -le '@array = ("a".."z"); print scalar @array'