Scripting Games 2007 Advanced PowerShell Event 6
Event 6: Give Me a (75-Column) Break
PS Answer: Give Me a (75-Column) Break
My Answer was not the much different only using
(gc alice.txt).split() |% {
To loop the words directly ( " " is default for split )
Script looks like this :
$t = ''
$length = 0
(gc alice.txt).split() |% {
if ($length -eq 0) {
$t += "$_"
$length = $_.Length
} Else {
if (($length + $_.length + 1) -le 75) {
$t += " $_"
$length += $_.Length + 1
}Else {
$t += "`n$_"
$length = $_.Length
}
}
}
$t
In parts like this :
PoSH> $t = ''
PoSH> $length = 0
PoSH> $Words = (gc alice.txt).split()
PoSH> $words | select -First 5
Curiouser
and
curiouser!'
cried
Alice
PoSH> $t += $Words[0]
PoSH> $t
Curiouser
PoSH> $length = $Words[0].Length
PoSH> $length
9
PoSH>
And in a loop :
PoSH> $length
9
PoSH> $length + $words[1].length + 1
13
PoSH> ($length + $words[1].length + 1) -le 75
True
PoSH> $t += " $($Words[1])"
PoSH> $t
Curiouser and
PoSH> $length += $Words[1].Length + 1
PoSH>
Note : $words[0] is the $_ in the loop for this example
Next loop :
PoSH> $length
9
PoSH> $length + $words[1].length + 1
13
PoSH> ($length + $words[1].length + 1) -le 75
True
PoSH> $t += " $($Words[1])"
PoSH> $t
Curiouser and
PoSH> $length += $Words[1].Length + 1
PoSH> Write-Warning "Example only Linebreak normaly at 75 Chars"
WARNING: Example only Linebreak normaly at 75 Chars
PoSH> $t += "`n$($Words[2])"
PoSH> $t
Curiouser and
curiouser!'
PoSH>
And Complete
PoSH> $t = ''
PoSH> $length = 0
PoSH> (gc alice.txt).split() |% {
>> if ($length -eq 0) {
>> $t += "$_"
>> $length = $_.Length
>> } Else {
>> if (($length + $_.length + 1) -le 75) {
>> $t += " $_"
>> $length += $_.Length + 1
>> }Else {
>> $t += "`n$_"
>> $length = $_.Length
>> }
>> }
>> }
>> $t
>>
Curiouser and curiouser!' cried Alice (she was so much surprised, that for
the moment she quite forgot how to speak good English); 'now I'm opening
out like the largest telescope that ever was! Good-bye, feet!' (for when
she looked down at her feet, they seemed to be almost out of sight, they
were getting so far off). 'Oh, my poor little feet, I wonder who will put
on your shoes and stockings for you now, dears? I'm sure _I_ shan't be
able! I shall be a great deal too far off to trouble myself about you: you
must manage the best way you can; --but I must be kind to them,' thought
Alice, 'or perhaps they won't walk the way I want to go! Let me see: I'll
give them a new pair of boots every Christmas.'
PoSH>
Enjoy,
Greetings /\/\o\/\/