Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Re: Web-Safe Color Chart

by trantor (Chaplain)
on Oct 05, 2001 at 14:19 UTC ( [id://116954]=note: print w/replies, xml ) Need Help??


in reply to Sneaky glob trick (was Web-Safe Color Chart)
in thread Web-Safe Color Chart

First of all, glob expands the pattern according to shell conventions, so

glob "foob{a,b,c}r"
returns the list
('foobar', 'foobbr', 'foobcr')
just like bash would return 'foobar foobbr foobcr' expandig metacharacters

The x operator applied to a string repeats the string the specified number of times, so

"{a,b,c}" x 3 evaluates as "{a,b,c}{a,b,c}{a,b,c}"

When you feed this expression to glob, the result is a list of all the possible combinations of a, b and c in a string of three characters, from 'aaa' to 'ccc'.

This could be easily achieved through magical string autoincrement, but the beauty of this method (very nice, I love it!) is that it applies to any set of strings to combine, not just characters.

-- TMTOWTDI

Replies are listed 'Best First'.
Re: Re: Re: Web-Safe Color Chart
by blakem (Monsignor) on Oct 05, 2001 at 14:41 UTC
    Thanks for the explanation... I've searched in vain for the node where I originally found this trick. Here is the code i squirrled away from it though:
    #!/usr/bin/perl print map "$_\n", glob("{A,B,C}{a,b,c}");
    I guess the part that puzzled me is that glob *usually* interacts with the filesystem. glob("*.pl") will return list of perl scripts in your cwd.... why aren't the values above checked against the filesystem for actual files?

    Update: The code above came from Re (tilly) 2: Sort of like a file handle, but not.

    -Blake

      Yes, this is somewhat unexpected for most people, but it turns out that shells (bash and tcsh at least) always expand a list enclosed in curly braces regardless of the presence of actual files.

      It is called Brace Expansion and it differs from Pathname Expansion in that file names need not exist (quoted from the bash manpage).

      You can verify easily with:

      $ ls {a,b,c} ls: a: No such file or directory ls: b: No such file or directory ls: c: No such file or directory $ ls [abc] ls: No match. $

      The fact that files do not have to exist is to be regarded as a feature, not as a bug, because you can say at the shell prompt something like (by the way, you can nest):

      $ mkdir -p {1999,2000,2001}/backup/{0{1,2,3,4,5,6,7,8,9},11,12}

      And get 36 directories created with one command.

      -- TMTOWTDI

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://116954]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-18 13:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found