Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write a version of this Go function in Tcl with identical behavior.
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo...
proc range {a {b ""}} { if {$b eq ""} { set b $a set a 0 } for {set r {}} {$a<$b} {incr a} { lappend r $a } return $r } proc lincr {_ls args} { upvar 1 $_ls ls set incr [lindex $args end] set idxs [lrange $args 0 end-1] lset ls {*}$idxs [expr {$incr + [l...
Preserve the algorithm and functionality while converting the code from Go to Tcl.
package main import ( "fmt" "github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre" ) var pattern = "(*UTF)(*UCP)" + "[a-z][-a-z0-9+.]*:" + "(?=[/\\w])" + "(?: "[-\\w.~/%!$&'()*+,;=]*" + "(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" ...
proc findURIs {text args} { set URI {(?x) [a-z][-a-z0-9+.]*: (?=[/\w]) (?://[-\w.@:]+)? [-\w.~/%!$&'()*+,;=]* (?:\?[-\w.~%!$&'()*+,;=/?]*)? (?:[ } regexp -inline -all {*}$args -- $URI $text }
Keep all operations the same but rewrite the snippet in Tcl.
package main import ( "fmt" "github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre" ) var pattern = "(*UTF)(*UCP)" + "[a-z][-a-z0-9+.]*:" + "(?=[/\\w])" + "(?: "[-\\w.~/%!$&'()*+,;=]*" + "(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" ...
proc findURIs {text args} { set URI {(?x) [a-z][-a-z0-9+.]*: (?=[/\w]) (?://[-\w.@:]+)? [-\w.~/%!$&'()*+,;=]* (?:\?[-\w.~%!$&'()*+,;=/?]*)? (?:[ } regexp -inline -all {*}$args -- $URI $text }
Please provide an equivalent version of this Go code in Tcl.
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "strings" "time" ) func get(url string) (res string, err error) { resp, err := http.Get(url) if err != nil { return "", err } buf, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(buf), nil } func grep(need...
package require http proc get url { set r [::http::geturl $url] set content [::http::data $r] ::http::cleanup $r return $content } proc grep {needle haystack} { lsearch -all \ -inline \ -glob \ [split $haystack \n] \ *[string map {* \\* ? \\? \\ \\\...
Generate a Tcl translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "crypto/md5" "io/ioutil" "log" "os" "path/filepath" "sort" "time" ) type fileData struct { filePath string info os.FileInfo } type hash [16]byte func check(err error) { if err != nil { log.Fatal(err) } } func checksum(filePath ...
package require fileutil package require md5 proc finddupfiles {dir {minsize 1}} { foreach fn [fileutil::find $dir] { file lstat $fn stat if {$stat(size) < $minsize} continue dict lappend byino $stat(dev),$stat(ino) $fn if {$stat(type) ne "file"} continue set f [open $fn "rb"] set content [...
Please provide an equivalent version of this Go code in Tcl.
package main import ( "fmt" "io/ioutil" "log" "os" "regexp" "strings" ) type header struct { start, end int lang string } type data struct { count int names *[]string } func newData(count int, name string) *data { return &data{count, &[]string{name}} } var bmap = m...
package require Tcl 8.5 package require http package require json package require textutil::split package require uri proc getUrlWithRedirect {base args} { set url $base?[http::formatQuery {*}$args] while 1 { set t [http::geturl $url] if {[http::status $t] ne "ok"} { error "Oops: url=$url\nstatus=$s\nht...
Rewrite this program in Tcl while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "strings" ) func isDigit(b byte) bool { return '0' <= b && b <= '9' } func separateHouseNumber(address string) (street string, house string) { length := len(address) fields := strings.Fields(address) size := len(fields) last := fields[size-1] penult := fiel...
proc split_DE_NL_address {streetAddress} { set RE {(?x) ^ (.*?) ( (?:\s \d+ [-/] \d+) | (?:\s (?!1940|1945)\d+ [a-zI. /]* \d*) )? $ } regexp $RE $streetAddress -> str num return [list [string trim $str] [string trim $num]] } set data { Plataanstraat 5 Straat 12 Straat 12 II ...
Translate this program into Tcl but keep the logic exactly as in Go.
package main import ( "fmt" "math" ) var ( d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6, 23.1, 19.6, 19.0, 21.7, 21.4} d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2, 21.9, 22.1, 22.9, 20.5, 24.4} d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21...
package require math::statistics package require math::special namespace path {::math::statistics ::math::special ::tcl::mathfunc ::tcl::mathop} proc incf {_var {inc 1.0}} { upvar 1 $_var var if {![info exists var]} { set var 0.0 } set var [expr {$inc + $var}] } proc sumfor {_var A B body} {...
Write the same code in Tcl as shown below in Go.
package main import ( "fmt" "math" ) var ( d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6, 23.1, 19.6, 19.0, 21.7, 21.4} d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2, 21.9, 22.1, 22.9, 20.5, 24.4} d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21...
package require math::statistics package require math::special namespace path {::math::statistics ::math::special ::tcl::mathfunc ::tcl::mathop} proc incf {_var {inc 1.0}} { upvar 1 $_var var if {![info exists var]} { set var 0.0 } set var [expr {$inc + $var}] } proc sumfor {_var A B body} {...
Write the same algorithm in Tcl as shown in this Go implementation.
package main import ( "fmt" "math" ) const ( N = 32 NMAX = 40000 ) var ( u = [N]int{0: 1, 1: 2} l = [N]int{0: 1, 1: 2} out = [N]int{} sum = [N]int{} tail = [N]int{} cache = [NMAX + 1]int{2: 1} known = 2 stack = 0 undo = [N * N]save{} ) type save...
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc minchain {n} { if {!($n & ($n-1))} { for {set i 1} {$i <= $n} {incr i $i} {lappend c $i} return $c } elseif {$n == 3} { return {1 2 3} } return [chain $n [expr {$n >> int(ceil(floor(log($n)/log(2))/2))}]] } proc chai...
Produce a language-to-language conversion: from Go to Tcl, same semantics.
package main import ( "fmt" "math" ) const ( N = 32 NMAX = 40000 ) var ( u = [N]int{0: 1, 1: 2} l = [N]int{0: 1, 1: 2} out = [N]int{} sum = [N]int{} tail = [N]int{} cache = [NMAX + 1]int{2: 1} known = 2 stack = 0 undo = [N * N]save{} ) type save...
package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::mathfunc} proc minchain {n} { if {!($n & ($n-1))} { for {set i 1} {$i <= $n} {incr i $i} {lappend c $i} return $c } elseif {$n == 3} { return {1 2 3} } return [chain $n [expr {$n >> int(ceil(floor(log($n)/log(2))/2))}]] } proc chai...
Ensure the translated Tcl code behaves exactly like the original Go snippet.
package cf import "math" type NG8 struct { A12, A1, A2, A int64 B12, B1, B2, B int64 } var ( NG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1} NG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1} NG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1} NG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0} ) func (ng *NG8) needsIngest() bool { if ng.B12 ...
oo::class create NG2 { variable a b a1 b1 a2 b2 a12 b12 cf1 cf2 superclass Generator constructor {args} { lassign $args a12 a1 a2 a b12 b1 b2 b next } method operands {N1 N2} { set cf1 $N1 set cf2 $N2 return [self] } method Ingress1 t { lassign [list [expr {$a2+$a12*$t}] [expr {$a+$a1...
Translate the given Go code snippet into Tcl without altering its behavior.
package cf import "math" type NG8 struct { A12, A1, A2, A int64 B12, B1, B2, B int64 } var ( NG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1} NG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1} NG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1} NG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0} ) func (ng *NG8) needsIngest() bool { if ng.B12 ...
oo::class create NG2 { variable a b a1 b1 a2 b2 a12 b12 cf1 cf2 superclass Generator constructor {args} { lassign $args a12 a1 a2 a b12 b1 b2 b next } method operands {N1 N2} { set cf1 $N1 set cf2 $N2 return [self] } method Ingress1 t { lassign [list [expr {$a2+$a12*$t}] [expr {$a+$a1...
Preserve the algorithm and functionality while converting the code from Go to Tcl.
package main import ( "fmt" "sort" ) type cf struct { c rune f int } func reverseStr(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func indexOfCf(cfs []cf, r rune) i...
package require Tcl 8.6 proc MostFreqKHashing {inputString k} { foreach ch [split $inputString ""] {dict incr count $ch} join [lrange [lsort -stride 2 -index 1 -integer -decreasing $count] 0 [expr {$k*2-1}]] "" } proc MostFreqKSimilarity {hashStr1 hashStr2} { while {$hashStr2 ne ""} { regexp {^(.)(\d+)(.*...
Ensure the translated Tcl code behaves exactly like the original Go snippet.
package main import ( "bufio" "crypto/rand" "fmt" "io/ioutil" "log" "math/big" "os" "strconv" "strings" "unicode" ) const ( charsPerLine = 48 chunkSize = 6 cols = 8 demo = true ) type fileType int const ( otp fileType = iota enc ...
puts " proc randInt { min max } { set randDev [open /dev/urandom rb] set random [read $randDev 8] binary scan $random H16 random set random [expr {([scan $random %x] % (($max-$min) + 1) + $min)}] close $randDev return $random } proc randStr { sLen grp alfa } { set aLen [string length $alfa];...
Maintain the same structure and functionality when rewriting this code in Tcl.
package main import ( "bufio" "crypto/rand" "fmt" "io/ioutil" "log" "math/big" "os" "strconv" "strings" "unicode" ) const ( charsPerLine = 48 chunkSize = 6 cols = 8 demo = true ) type fileType int const ( otp fileType = iota enc ...
puts " proc randInt { min max } { set randDev [open /dev/urandom rb] set random [read $randDev 8] binary scan $random H16 random set random [expr {([scan $random %x] % (($max-$min) + 1) + $min)}] close $randDev return $random } proc randStr { sLen grp alfa } { set aLen [string length $alfa];...
Convert this Go snippet to Tcl and keep its semantics consistent.
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err ...
package require Tcl 8.5 proc topsort {data} { dict for {node depends} $data { if {[set i [lsearch -exact $depends $node]] >= 0} { set depends [lreplace $depends $i $i] dict set data $node $depends } foreach node $depends {dict lappend data $node} } s...
Generate a Tcl translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err ...
package require Tcl 8.5 proc topsort {data} { dict for {node depends} $data { if {[set i [lsearch -exact $depends $node]] >= 0} { set depends [lreplace $depends $i $i] dict set data $node $depends } foreach node $depends {dict lappend data $node} } s...
Generate a Tcl translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "sort" ) type ( Point [3]float64 Face []int Edge struct { pn1 int pn2 int fn1 int fn2 int cp Point } PointEx struct { p Point n int } ) func sumPoint(p1, p2 Point) Point { sp := Po...
package require Tcl 8.5 namespace path {tcl::mathfunc tcl::mathop} proc add3 {A B C} { lassign $A Ax Ay Az lassign $B Bx By Bz lassign $C Cx Cy Cz list [+ $Ax $Bx $Cx] [+ $Ay $By $Cy] [+ $Az $Bz $Cz] } proc mulC {m A} { lassign $A x y z list [* $m $x] [* $m $y] [* $m $z] } proc centroi...
Convert this Go snippet to Tcl and keep its semantics consistent.
package main import ( "fmt" "html/template" "log" "os" "os/exec" "strings" "time" ) type row struct { Address, Street, House, Color string } func isDigit(b byte) bool { return '0' <= b && b <= '9' } func separateHouseNumber(address string) (street string, house string) { leng...
package require Tcl 8.6 proc split_DE_NL_address {streetAddress} { set RE {(?x) ^ (.*?) ( (?:\s \d+ [-/] \d+) | (?:\s (?!1940|1945)\d+ [a-zI. /]* \d*) )? $ } regexp $RE $streetAddress -> str num return [list [string trim $str] [string trim $num]] } set data { Plataanstraat 5 Stra...
Port the provided Go code into Tcl while preserving the original functionality.
package main import ( "fmt" "math/big" ) func repeatedAdd(bf *big.Float, times int) *big.Float { if times < 2 { return bf } var sum big.Float for i := 0; i < times; i++ { sum.Add(&sum, bf) } return &sum } func main() { s := "12345679" t := "123456790" e := ...
namespace path ::tcl::mathop for {set n -7; set e 63} {$n <= 21} {incr n;incr e -9} { append m 012345679 puts $n:[+ [* [format "%se%s" $m $e] 81] 1e${e}] }
Transform the following Go implementation into Tcl, maintaining the same output and logic.
package main import ( "fmt" "math/big" ) func repeatedAdd(bf *big.Float, times int) *big.Float { if times < 2 { return bf } var sum big.Float for i := 0; i < times; i++ { sum.Add(&sum, bf) } return &sum } func main() { s := "12345679" t := "123456790" e := ...
namespace path ::tcl::mathop for {set n -7; set e 63} {$n <= 21} {incr n;incr e -9} { append m 012345679 puts $n:[+ [* [format "%se%s" $m $e] 81] 1e${e}] }
Write the same code in Tcl as shown below in Go.
package main import ( "bufio" "fmt" "io" "io/ioutil" "regexp" "sort" "strings" ) var fs = make(map[string]string) type file struct{ name string } func (f file) Write(p []byte) (int, error) { fs[f.name] += string(p) return len(p), nil } func toName(name string, src io.Reade...
package require Tcl 8.6 proc aspipe {input cmd args} { tailcall coroutine pipe[incr ::pipes] eval {yield [info coroutine];} \ [list $cmd $input {*}$args] {;break} } proc forpipe {input var body} { upvar 1 $var v while {[llength [info commands $input]]} { set v [$input] uplevel 1 $body } } proc pi...
Rewrite this program in Tcl while keeping its functionality equivalent to the Go version.
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) freq := 0 for freq < 40 || freq > 10000 { fmt.Print("Enter frequency in Hz (4...
package require sound set baseFrequency 261.63 set baseAmplitude [expr {64000 / 100.0}] set halfSemis 0 set volSteps 10 proc adjustPitchVolume {changePitch changeVolume} { global filter baseFrequency baseAmplitude halfSemis volSteps incr halfSemis $changePitch incr volSteps $changeVolume set vol...
Translate the given Go code snippet into Tcl without altering its behavior.
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) freq := 0 for freq < 40 || freq > 10000 { fmt.Print("Enter frequency in Hz (4...
package require sound set baseFrequency 261.63 set baseAmplitude [expr {64000 / 100.0}] set halfSemis 0 set volSteps 10 proc adjustPitchVolume {changePitch changeVolume} { global filter baseFrequency baseAmplitude halfSemis volSteps incr halfSemis $changePitch incr volSteps $changeVolume set vol...
Write the same code in Tcl as shown below in Go.
package main import ( "crypto/tls" "io/ioutil" "log" "net/http" ) func main() { cert, err := tls.LoadX509KeyPair( "./client.local.tld/client.local.tld.crt", "./client.local.tld/client.local.tld.key", ) if err != nil { log.Fatal("Error while loading x509 key pair", err) } tlsConfig := &tls.Config...
package require http package require tls set cert myCert.p12 http::register https 443 [list \ ::tls::socket -certfile $cert -password getPass] proc getPass {} { return "myPassword"; } set token [http::geturl https://verysecure.example.com/] set data [http::data $token] http::cleanup $token
Generate a Tcl translation of this Go snippet without changing its computational steps.
package main import ( "bytes" "crypto/md5" "crypto/rand" "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func connectDB() (*sql.DB, error) { return sql.Open("mysql", "rosetta:code@/rc") } func createUser(db *sql.DB, user, pwd string) error { salt := make([]byte, 16) ran...
package require tdbc proc connect_db {handleName dbname host user pass} { package require tdbc::mysql tdbc::mysql::connection create $handleName -user $user -passwd $pass \ -host $host -database $dbname return $handleName } proc r64k {} { expr int(65536*rand()) } proc create_user {handle use...
Generate a Tcl translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/rand" "os/exec" "raster" ) func main() { b := raster.NewBitmap(400, 300) b.FillRgb(0xc08040) for i := 0; i < 2000; i++ { b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020) } for x := 0; x < 400; x++ { for y := 240; y < 24...
package require Tk proc output_jpeg {image filename {quality 75}} { set f [open |[list convert ppm:- -quality $quality jpg:- > $filename] w] fconfigure $f -translation binary puts -nonewline $f [$image data -format ppm] close $f }
Write the same algorithm in Tcl as shown in this Go implementation.
package onetime import ( "crypto/hmac" "crypto/sha1" "encoding/binary" "errors" "hash" "math" "time" ) type OneTimePassword struct { Digit int TimeStep time.Duration BaseTime time.Time Hash func() hash.Hash } func (otp *OneTimePassword) HOTP(secret []byte, count uint...
catch {namespace delete ::totp} namespace eval ::totp { package require sha1 oo::class create totp { variable Secret variable Interval variable Window constructor {secret {interval 30} {window 300}} { if {![string is digit $interval]} { set inter...
Keep all operations the same but rewrite the snippet in Tcl.
package main import ( "fmt" "html" "regexp" "strings" ) var t = ` Sample Text This is an example of converting plain text to HTML which demonstrates extracting a title and escaping certain characters within bulleted and numbered lists. * This is a bulleted list with a less than sign (<) * And t...
package require Tcl 8.5 proc splitParagraphs {text} { split [regsub -all {\n\s*(\n\s*)+} [string trim $text] \u0000] "\u0000" } proc determineParagraph {para} { set para [regsub -all {\s*\n\s*} $para " "] switch -regexp -- $para { {^\s*\*+\s} { return [list ul [string trimleft $para " \t*"]] } {^\s...
Generate a Tcl translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "html" "regexp" "strings" ) var t = ` Sample Text This is an example of converting plain text to HTML which demonstrates extracting a title and escaping certain characters within bulleted and numbered lists. * This is a bulleted list with a less than sign (<) * And t...
package require Tcl 8.5 proc splitParagraphs {text} { split [regsub -all {\n\s*(\n\s*)+} [string trim $text] \u0000] "\u0000" } proc determineParagraph {para} { set para [regsub -all {\s*\n\s*} $para " "] switch -regexp -- $para { {^\s*\*+\s} { return [list ul [string trimleft $para " \t*"]] } {^\s...
Port the following code from Go to Tcl with equivalent syntax and logic.
package main import ( "fmt" "reflect" "unsafe" ) func main() { bs := []byte("Hello world!") fmt.Println(string(bs)) g := "globe" hdr := (*reflect.SliceHeader)(unsafe.Pointer(&bs)) for i := 0; i < 5; i++ { data := (*byte)(unsafe.Pointer(hdr.Data + uintptr(i) + 6)) *data ...
set context [interp create -safe] $context eval $untrustedCode
Convert the following code from Go to Tcl, ensuring the logic remains intact.
package main import ( "fmt" "github.com/sevlyar/go-daemon" "log" "os" "time" ) func work() { f, err := os.Create("daemon_output.txt") if err != nil { log.Fatal(err) } defer f.Close() ticker := time.NewTicker(time.Second) go func() { for t := range ticker.C {...
package provide daemon 1 package require critcl critcl::ccode { } critcl::cproc daemon {Tcl_Interp* interp} ok { if (daemon(0, 0) < 0) { Tcl_AppendResult(interp, "cannot switch to daemon operation: ", Tcl_PosixError(interp), NULL); return TCL_ERROR; } return TCL_OK; }
Generate a Tcl translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "github.com/sevlyar/go-daemon" "log" "os" "time" ) func work() { f, err := os.Create("daemon_output.txt") if err != nil { log.Fatal(err) } defer f.Close() ticker := time.NewTicker(time.Second) go func() { for t := range ticker.C {...
package provide daemon 1 package require critcl critcl::ccode { } critcl::cproc daemon {Tcl_Interp* interp} ok { if (daemon(0, 0) < 0) { Tcl_AppendResult(interp, "cannot switch to daemon operation: ", Tcl_PosixError(interp), NULL); return TCL_ERROR; } return TCL_OK; }
Produce a language-to-language conversion: from Go to Tcl, same semantics.
package main import ( "bufio" "fmt" "html" "io/ioutil" "log" "net/http" "os" "os/exec" "regexp" "strings" ) func getAllTasks() map[string]bool { ex := `<li><a href="/wiki/(.*?)"` re := regexp.MustCompile(ex) url1 := "http: url2 := "http: urls := []string{url...
package require Tcl 8.5 package require http package require uri proc getUrlWithRedirect {base args} { set url $base?[http::formatQuery {*}$args] while 1 { set t [http::geturl $url] if {[http::status $t] ne "ok"} { error "Oops: url=$url\nstatus=$s\nhttp code=[http::code $token]" } if {[string match 2...
Maintain the same structure and functionality when rewriting this code in Tcl.
package main import ( "bufio" "fmt" "html" "io/ioutil" "log" "net/http" "os" "os/exec" "regexp" "strings" ) func getAllTasks() map[string]bool { ex := `<li><a href="/wiki/(.*?)"` re := regexp.MustCompile(ex) url1 := "http: url2 := "http: urls := []string{url...
package require Tcl 8.5 package require http package require uri proc getUrlWithRedirect {base args} { set url $base?[http::formatQuery {*}$args] while 1 { set t [http::geturl $url] if {[http::status $t] ne "ok"} { error "Oops: url=$url\nstatus=$s\nhttp code=[http::code $token]" } if {[string match 2...
Write a version of this Go function in Tcl with identical behavior.
package main import ( "fmt" "github.com/beevik/etree" "log" "os" "strconv" "strings" ) type animData struct { element *etree.Element attrib string from string to string begin float64 dur float64 } func check(err error) { if err != nil { log.F...
package require Tcl 8.6 package require tdom proc interpolate {time info} { dict with info { scan $begin "%fs" begin scan $dur "%fs" dur } if {$time < $begin} { return $from } elseif {$time > $begin+$dur} { return $to } set delta [expr {($time - $begin) / $dur}] return [lmap f $from t ...
Convert the following code from Go to Tcl, ensuring the logic remains intact.
package main import ( "fmt" "io" "log" "os" "sync/atomic" "syscall" ) const ( inputFifo = "/tmp/in.fifo" outputFifo = "/tmp/out.fifo" readsize = 64 << 10 ) func openFifo(path string, oflag int) (f *os.File, err error) { err = syscall....
exec sh -c {test -p in || mkfifo in || exit 1;test -p out || exec mkfifo out} set count 0 set in [open in {RDONLY NONBLOCK}] fconfigure $in -translation binary fileevent $in readable consume proc consume {} { global count in set data [read $in 4096] incr count [string length $data] } proc report...
Rewrite the snippet below in Tcl so it works the same as the original Go code.
package world import ( "bytes" "fmt" "log" "ra/ifc" ) var maze = []byte(` WWWWWWWWWWWWWWWW W W W W W W W Rb W Rg B W W W W W W G G B G W W W W W W Br G W R W W W ^ W W W ...
package require TclOO proc pick list { lindex $list [expr {int([llength $list] * rand())}] } proc callback {method args} { list [uplevel 1 {namespace current}]::my $method {*}$args } proc bgerror args {puts stderr $args} oo::class create BallMaze { variable grid balls x y dir carry turns identity chan...
Write a version of this Go function in Tcl with identical behavior.
package agent import ( "log" "math/rand" "time" "ra/ifc" ) var sectorColor, sectorBall, agentBall byte var stream ifc.Streamer func Agent(s ifc.Streamer) { stream = s rand.Seed(time.Now().Unix()) hs := stream.Rec() if hs != ifc.Handshake { log.Fatal("agent: t...
package require Tcl 8.6 package require RC::RemoteAgent oo::class create Agent { superclass AgentAPI variable sectorColor ballColor forward Behavior my MoveBehavior method MoveBehavior {} { set ball "" while 1 { try { while {rand() < 0.5} { my ForwardStep my BallBehavior } ...
Port the following code from Go to Tcl with equivalent syntax and logic.
package main import "C" import "log" import "unsafe" var ps, vs, prog, r_mod C.GLuint var angle = float32(0) func render() { C.glClear(C.GL_COLOR_BUFFER_BIT) C.glUniform1f_macro(C.GLint(r_mod), C.GLfloat(C.rand())/C.GLfloat(C.RAND_MAX)) C.glLoadIdentity() C.glRotatef(C.float(angle), C.float(angle*0...
package require tcl3d proc mkshader {type src} { set sh [glCreateShader $type] tcl3dOglShaderSource $sh $src glCompileShader $sh puts "compilation report : [tcl3dOglGetShaderState $sh $::GL_COMPILE_STATUS] [tcl3dOglGetShaderInfoLog $sh]" return $sh } proc render {{angle 0}} { glClear $::GL_COL...
Translate this program into Tcl but keep the logic exactly as in Go.
package main import ( "fmt" "strings" ) type object = interface{} type sequence = []object var ( src []rune ch rune sdx int token object isSeq bool err = false idents []string ididx []int productions []sequence e...
package require Tcl 8.6 proc provide args {while {![yield $args]} {yield}} proc next lexer {$lexer 1} proc pushback lexer {$lexer 0} proc lexer {str} { yield [info coroutine] set symbols {+ PLUS - MINUS * MULT / DIV ( LPAR ) RPAR} set idx 0 while 1 { switch -regexp -matchvar m -- $str { {^\s+}...
Write the same code in Tcl as shown below in Go.
package main import ( "fmt" "strings" ) type object = interface{} type sequence = []object var ( src []rune ch rune sdx int token object isSeq bool err = false idents []string ididx []int productions []sequence e...
package require Tcl 8.6 proc provide args {while {![yield $args]} {yield}} proc next lexer {$lexer 1} proc pushback lexer {$lexer 0} proc lexer {str} { yield [info coroutine] set symbols {+ PLUS - MINUS * MULT / DIV ( LPAR ) RPAR} set idx 0 while 1 { switch -regexp -matchvar m -- $str { {^\s+}...
Write the same algorithm in Tcl as shown in this Go implementation.
package main import ( "crypto/tls" "fmt" "github.com/thoj/go-ircevent" "log" "os" ) func main() { if len(os.Args) != 9 { fmt.Println("To use this gateway, you need to pass 8 command line arguments, namely:") fmt.Println(" <server1> <channel1> <nick1> <user1> <server2> <channel...
package require picoirc if {$argc != 4} { puts stderr "wrong exit 1 } lassign $argv url1 nick1 url2 nick2 proc handle {from to -> state args} { upvar switch -exact -- $state { "chat" { lassign $args target nick message type if {![string match "*>>*<<*" $message]} { picoirc::post $t ...
Ensure the translated Tcl code behaves exactly like the original Go snippet.
package main import ( "crypto/tls" "fmt" "github.com/thoj/go-ircevent" "log" "os" ) func main() { if len(os.Args) != 9 { fmt.Println("To use this gateway, you need to pass 8 command line arguments, namely:") fmt.Println(" <server1> <channel1> <nick1> <user1> <server2> <channel...
package require picoirc if {$argc != 4} { puts stderr "wrong exit 1 } lassign $argv url1 nick1 url2 nick2 proc handle {from to -> state args} { upvar switch -exact -- $state { "chat" { lassign $args target nick message type if {![string match "*>>*<<*" $message]} { picoirc::post $t ...
Keep all operations the same but rewrite the snippet in Tcl.
package ifc type Streamer interface { Send(byte) Rec() byte } const Handshake = 'A' const ( CmdForward = '^' CmdRight = '>' CmdLeft = '<' CmdGet = '@' CmdDrop = '!' EvGameOver = '+' EvStop = '.' EvColorRed ...
package require Tcl 8.6 oo::class create AgentAPI { variable sock events sectorColor ballColor constructor {host port} { set sock [socket $host $port] fconfigure $sock -buffering none -translation binary -encoding ascii \ -blocking 0 if {![llength [info commands yieldto]]} { interp alias ...
Write a version of this PHP function in Perl with identical behavior.
<?php header("Content-type: image/png"); $width = 512; $height = 512; $img = imagecreatetruecolor($width,$height); $bg = imagecolorallocate($img,255,255,255); imagefilledrectangle($img, 0, 0, $width, $width, $bg); $depth = 8; function drawTree($x1, $y1, $angle, $depth){ global $img; if ($depth != 0)...
use GD::Simple; my ($width, $height) = (1000,1000); my $scale = 6/10; my $length = 400; my $img = GD::Simple->new($width,$height); $img->fgcolor('black'); $img->penSize(1,1); tree($width/2, $height, $length, 270); print $img->png; sub tree { my ($x, $y, $len, $angle) = @_; return if $len < 1; ...
Write a version of this PHP function in Perl with identical behavior.
<?php echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>"; echo "<h2>"; echo ""; $player = strtoupper( $_GET["moves"] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo "<br>"; echo "Player chooses " . "<i style=\"color:blue\">" . $player ....
use 5.012; use warnings; use utf8; use open qw(:encoding(utf-8) :std); use Getopt::Long; package Game { use List::Util qw(shuffle first); my $turns = 0; my %human_choice = ( rock => 0, paper => 0, scissors => 0, ); my %comp_choice = ( rock => 0, paper => 0, scissors => 0, ); my %what_beats...
Generate a Perl translation of this PHP snippet without changing its computational steps.
<?php $conf = file_get_contents('parse-conf-file.txt'); $conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf); $conf = preg_replace_callback( '/^([a-z]+)\s*=((?=.*\,.*).*)$/mi', function ($matches) { $r = ''; foreach (explode(',', $matches[2]) AS $val) { $r .= $matches[1] . '[]...
my $fullname; my $favouritefruit; my $needspeeling; my $seedsremoved; my @otherfamily; my $conf_definition = { 'fullname' => [ 'string', \$fullname ], 'favouritefruit' => [ 'string', \$favouritefruit ], 'needspeeling' => [ 'boolean', \$needspeeling ], 'seedsremoved' => [ 'boolean...
Transform the following PHP implementation into Perl, maintaining the same output and logic.
<?php $dog = 'Benjamin'; $Dog = 'Samba'; $DOG = 'Bernie'; echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n"; function DOG() { return 'Bernie'; } echo 'There is only 1 dog named ' . dog() . "\n";
$dog='Benjamin'; $Dog='Samba'; $DOG='Bernie'; print "The three dogs are named $dog, $Dog, and $DOG \n"
Translate this program into Perl but keep the logic exactly as in PHP.
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase ...
@c = (join ' ', qw< Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LP...
Convert this PHP block to Perl, preserving its control flow and logic.
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase ...
@c = (join ' ', qw< Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LP...
Can you help me rewrite this code in Perl instead of PHP, keeping it the same logically?
function stoogeSort(&$arr, $i, $j) { if($arr[$j] < $arr[$i]) { list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); } if(($j - $i) > 1) { $t = ($j - $i + 1) / 3; stoogesort($arr, $i, $j - $t); stoogesort($arr, $i + $t, $j); stoogesort($arr, $i, $j - $t); } }
sub stooge { use integer; my ($x, $i, $j) = @_; $i //= 0; $j //= $ if ( $x->[$j] < $x->[$i] ) { @$x[$i, $j] = @$x[$j, $i]; } if ( $j - $i > 1 ) { my $t = ($j - $i + 1) / 3; stooge( $x, $i, $j - $t ); ...
Rewrite the snippet below in Perl so it works the same as the original PHP code.
function shellSort($arr) { $inc = round(count($arr)/2); while($inc > 0) { for($i = $inc; $i < count($arr);$i++){ $temp = $arr[$i]; $j = $i; while($j >= $inc && $arr[$j-$inc] > $temp) { $arr[$j] = $arr[$j - $inc]; $j -= $inc; } $arr[$j] = $temp; } $inc = round($inc/2.2); } return $ar...
sub shell_sort { my (@a, $h, $i, $j, $k) = @_; for ($h = @a; $h = int $h / 2;) { for $i ($h .. $ $k = $a[$i]; for ($j = $i; $j >= $h && $k < $a[$j - $h]; $j -= $h) { $a[$j] = $a[$j - $h]; } $a[$j] = $k; } } @a; } my @a = ma...
Change the programming language of this snippet from PHP to Perl without modifying what it does.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOC...
while (<>) { $. == $n and print, exit } die "file too short\n";
Translate this program into Perl but keep the logic exactly as in PHP.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOC...
while (<>) { $. == $n and print, exit } die "file too short\n";
Preserve the algorithm and functionality while converting the code from PHP to Perl.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
sub urlencode { my $s = shift; $s =~ s/([^-A-Za-z0-9_.!~*'() ])/sprintf("%%%02X", ord($1))/eg; $s =~ tr/ /+/; return $s; } print urlencode('http://foo bar/')."\n";
Port the provided PHP code into Perl while preserving the original functionality.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
sub urlencode { my $s = shift; $s =~ s/([^-A-Za-z0-9_.!~*'() ])/sprintf("%%%02X", ord($1))/eg; $s =~ tr/ /+/; return $s; } print urlencode('http://foo bar/')."\n";
Port the following code from PHP to Perl with equivalent syntax and logic.
<?php function f($n) { return sqrt(abs($n)) + 5 * $n * $n * $n; } $sArray = []; echo "Enter 11 numbers.\n"; for ($i = 0; $i <= 10; $i++) { echo $i + 1, " - Enter number: "; array_push($sArray, (float)fgets(STDIN)); } echo PHP_EOL; $sArray = array_reverse($sArray); foreach ($sArray as $s) { $r = ...
print "Enter 11 numbers:\n"; for ( 1..11 ) { $number = <STDIN>; chomp $number; push @sequence, $number; } for $n (reverse @sequence) { my $result = sqrt( abs($n) ) + 5 * $n**3; printf "f( %6.2f ) %s\n", $n, $result > 400 ? " too large!" : sprintf "= %6.2f", $result }
Rewrite this program in Perl while keeping its functionality equivalent to the PHP version.
$odd = function ($prev) use ( &$odd ) { $a = fgetc(STDIN); if (!ctype_alpha($a)) { $prev(); fwrite(STDOUT, $a); return $a != '.'; } $clos = function () use ($a , $prev) { fwrite(STDOUT, $a); $prev(); }; return $odd($clos); }; $even = function () { while (true) { $c = fgetc(STDIN); fwrite(STDOUT, $c...
sub r { my ($f, $c) = @_; return sub { print $c; $f->(); }; } $r = sub {}; while (read STDIN, $_, 1) { $w = /^[a-zA-Z]$/; $n++ if ($w && !$l); $l = $w; if ($n & 1 || !$w) { $r->(); $r = sub{}; print; } else { $r = r($r, $_); } } $r->();
Port the following code from PHP to Perl with equivalent syntax and logic.
<?php function is_describing($number) { foreach (str_split((int) $number) as $place => $value) { if (substr_count($number, $place) != $value) { return false; } } return true; } for ($i = 0; $i <= 50000000; $i += 10) { if (is_describing($i)) { echo $i . PHP_EOL;...
sub is_selfdesc { local $_ = shift; my @b = (0) x length; $b[$_]++ for my @a = split //; return "@a" eq "@b"; } for (0 .. 100000, 3211000, 42101000) { print "$_\n" if is_selfdesc($_); }
Transform the following PHP implementation into Perl, maintaining the same output and logic.
<?php $n = 9; // the number of rows for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $n; $j++) { echo ($i == $j || $i == $n - $j + 1) ? ' 1' : ' 0'; } echo "\n"; }
use strict; use warnings; print diagonal($_), "\n" for 10, 11; sub diagonal { my $n = shift() - 1; local $_ = 1 . 0 x ($n - 1) . 2 . "\n" . (0 . 0 x $n . "\n") x $n; 1 while s/(?<=1...{$n})0/1/s or s/(?<=2.{$n})[01]/2/s; return tr/2/1/r =~ s/\B/ /gr; }
Translate this program into Perl but keep the logic exactly as in PHP.
<?php foreach(file("unixdict.txt") as $w) echo (strstr($w, "the") && strlen(trim($w)) > 11) ? $w : "";
/Code$ perl -n -e '/(\w*the\w*)/ && length($1)>11 && print' unixdict.txt authenticate chemotherapy chrysanthemum clothesbrush clotheshorse eratosthenes featherbedding featherbrain featherweight gaithersburg hydrothermal lighthearted mathematician neurasthenic nevertheless northeastern northernmost otherworldly parasymp...
Convert this PHP block to Perl, preserving its control flow and logic.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
$address = <<END; 1, High Street, $town_name, West Midlands. WM4 5HD. END
Port the provided PHP code into Perl while preserving the original functionality.
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
$address = <<END; 1, High Street, $town_name, West Midlands. WM4 5HD. END
Keep all operations the same but rewrite the snippet in Perl.
<?php $game = new Game(); while(true) { $game->cycle(); } class Game { private $field; private $fieldSize; private $command; private $error; private $lastIndexX, $lastIndexY; private $score; private $finishScore; function __construct() { $this->field = array(); $this->fieldSize = 4; $this->finishS...
use strict; use warnings; use Tk; my $N = shift // 4; $N < 2 and $N = 2; my @squares = 1 .. $N*$N; my %n2ch = (' ' => ' '); @n2ch{ map 2**$_, 1..26} = 'a'..'z'; my %ch2n = reverse %n2ch; my $winner = ''; my @arow = 0 .. $N - 1; my @acol = map $_ * $N, @arow; my $mw = MainWindow->new; $mw->geometry( '+300+0' ); $mw...
Write a version of this PHP function in Perl with identical behavior.
function sattoloCycle($items) { for ($i = 0; $i < count($items); $i++) { $j = floor((mt_rand() / mt_getrandmax()) * $i); $tmp = $items[$i]; $items[$i] = $items[$j]; $items[$j] = $tmp; } return $items; }
@a = 0..30; printf "%2d ", $_ for @a; print "\n"; sattolo_cycle(\@a); printf "%2d ", $_ for @a; print "\n"; sub sattolo_cycle { my($array) = @_; for $i (reverse 0 .. -1+@$array) { my $j = int rand $i; @$array[$j, $i] = @$array[$i, $j]; } }
Port the provided PHP code into Perl while preserving the original functionality.
function sattoloCycle($items) { for ($i = 0; $i < count($items); $i++) { $j = floor((mt_rand() / mt_getrandmax()) * $i); $tmp = $items[$i]; $items[$i] = $items[$j]; $items[$j] = $tmp; } return $items; }
@a = 0..30; printf "%2d ", $_ for @a; print "\n"; sattolo_cycle(\@a); printf "%2d ", $_ for @a; print "\n"; sub sattolo_cycle { my($array) = @_; for $i (reverse 0 .. -1+@$array) { my $j = int rand $i; @$array[$j, $i] = @$array[$i, $j]; } }
Rewrite the snippet below in Perl so it works the same as the original PHP code.
$server = "speedtest.tele2.net"; $user = "anonymous"; $pass = "ftptest@example.com"; $conn = ftp_connect($server); if (!$conn) { die('unable to connect to: '. $server); } $login = ftp_login($conn, $user, $pass); if (!$login) { echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass; } e...
use Net::FTP; my $host = 'speedtest.tele2.net'; my $user = 'anonymous'; my $password = ''; my $f = Net::FTP->new($host) or die "Can't open $host\n"; $f->login($user, $password) or die "Can't login as $user\n"; $f->passive(); $f->cwd('upload'); @files = $f->ls(); printf "Currently %d files in the 'upload'...
Write a version of this PHP function in Perl with identical behavior.
<?php $db = new SQLite3(':memory:'); $db->exec(" CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL ) "); ?>
use DBI; my $db = DBI->connect('DBI:mysql:database:server','login','password'); my $statment = <<EOF; CREATE TABLE `Address` ( `addrID` int(11) NOT NULL auto_increment, `addrStreet` varchar(50) NOT NULL default '', `addrCity` varchar(25) NOT NULL default '', `addrState` char(2...
Change the following PHP code into Perl without altering its purpose.
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed...
use bignum; $max = 1000; $remaining += $_ for 1..$max; my @recamans = 0; my $previous = 0; while ($remaining > 0) { $term++; my $this = $previous - $term; $this = $previous + $term unless $this > 0 and !$seen{$this}; push @recamans, $this; $dup = $term if !$dup and defined $seen{$this}; $remaining ...
Write the same algorithm in Perl as shown in this PHP implementation.
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed...
use bignum; $max = 1000; $remaining += $_ for 1..$max; my @recamans = 0; my $previous = 0; while ($remaining > 0) { $term++; my $this = $previous - $term; $this = $previous + $term unless $this > 0 and !$seen{$this}; push @recamans, $this; $dup = $term if !$dup and defined $seen{$this}; $remaining ...
Write a version of this PHP function in Perl with identical behavior.
<?php function Y($f) { $g = function($w) use($f) { return $f(function() use($w) { return call_user_func_array($w($w), func_get_args()); }); }; return $g($g); } $fibonacci = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); }; }); echo $fibonacci(10), "...
sub Y { my $f = shift; sub { my $x = shift; $x->($x) }->( sub {my $y = shift; $f->(sub {$y->($y)(@_)})} ) } my $fac = sub {my $f = shift; sub {my $n = shift; $n < 2 ? 1 : $n * $f->($n-1)} }; my $fib = sub {my $f = shift; sub {my $n = shift; $n == 0 ? 0 :...
Produce a functionally identical Perl code for the snippet given in PHP.
<?php function columns($arr) { if (count($arr) == 0) return array(); else if (count($arr) == 1) return array_chunk($arr[0], 1); array_unshift($arr, NULL); $transpose = call_user_func_array('array_map', $arr); return array_map('array_filter', $transpose); } function beadsort($arr) ...
sub beadsort { my @data = @_; my @columns; my @rows; for my $datum (@data) { for my $column ( 0 .. $datum-1 ) { ++ $rows[ $columns[$column]++ ]; } } return reverse @rows; } beadsort 5, 7, 1, 3, 1, 1, 20;
Translate the given PHP code snippet into Perl without altering its behavior.
$accumulator = 0; echo 'HQ9+: '; $program = trim(fgets(STDIN)); foreach (str_split($program) as $chr) { switch ($chr) { case 'H': case 'h': printHelloWorld(); break; case 'Q': case 'q': printSource($program); break; case '9': ...
use warnings; use strict; use feature qw(say switch); my @programme = <> or die "No input. Specify a program file or pipe it to the standard input.\n"; for (@programme) { for my $char (split //) { given ($char) { when ('H') { hello() } when ('Q') { quinne(@programme) ...
Rewrite this program in Perl while keeping its functionality equivalent to the PHP version.
$accumulator = 0; echo 'HQ9+: '; $program = trim(fgets(STDIN)); foreach (str_split($program) as $chr) { switch ($chr) { case 'H': case 'h': printHelloWorld(); break; case 'Q': case 'q': printSource($program); break; case '9': ...
use warnings; use strict; use feature qw(say switch); my @programme = <> or die "No input. Specify a program file or pipe it to the standard input.\n"; for (@programme) { for my $char (split //) { given ($char) { when ('H') { hello() } when ('Q') { quinne(@programme) ...
Preserve the algorithm and functionality while converting the code from PHP to Perl.
<?php function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) { do { switch($s[$_s]) { case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break; case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break; case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break; case '<': $_d--; break; ...
my %code = split ' ', <<'END'; > $ptr++ < $ptr-- + $memory[$ptr]++ - $memory[$ptr]-- , $memory[$ptr]=ord(getc) . print(chr($memory[$ptr])) [ while($memory[$ptr]){ ] } END my ($ptr, @memory) = 0; eval join ';', map @code{ /./g }, <>;
Rewrite this program in Perl while keeping its functionality equivalent to the PHP version.
<?php function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) { do { switch($s[$_s]) { case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break; case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break; case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break; case '<': $_d--; break; ...
my %code = split ' ', <<'END'; > $ptr++ < $ptr-- + $memory[$ptr]++ - $memory[$ptr]-- , $memory[$ptr]=ord(getc) . print(chr($memory[$ptr])) [ while($memory[$ptr]){ ] } END my ($ptr, @memory) = 0; eval join ';', map @code{ /./g }, <>;
Preserve the algorithm and functionality while converting the code from PHP to Perl.
class Card { protected static $suits = array( '♠', '♥', '♦', '♣' ); protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); protected $suit; protected $suitOrder; protected $pip; protected $pipOrder; protected $order; public function __c...
package Playing_Card_Deck; use strict; use warnings; @Playing_Card_Deck::suits = qw [Diamonds Clubs Hearts Spades]; @Playing_Card_Deck::pips = qw [Two Three Four Five Six Seven Eight Nine Ten Jack King Queen Ace]; sub new {my $invocant = shift; my $class = ref($invocant) || $invocant; my @cards; ...
Preserve the algorithm and functionality while converting the code from PHP to Perl.
<?php class Foo { public function __clone() { $this->child = clone $this->child; } } $object = new Foo; $object->some_value = 1; $object->child = new stdClass; $object->child->some_value = 1; $deepcopy = clone $object; $deepcopy->some_value++; $deepcopy->child->some_value++; echo "Object contains...
use strict; use warnings; use Storable; use Data::Dumper; my $src = { foo => 0, bar => [0, 1] }; $src->{baz} = $src; my $dst = Storable::dclone($src); print Dumper($src); print Dumper($dst);
Produce a language-to-language conversion: from PHP to Perl, same semantics.
<?php class Foo { public function __clone() { $this->child = clone $this->child; } } $object = new Foo; $object->some_value = 1; $object->child = new stdClass; $object->child->some_value = 1; $deepcopy = clone $object; $deepcopy->some_value++; $deepcopy->child->some_value++; echo "Object contains...
use strict; use warnings; use Storable; use Data::Dumper; my $src = { foo => 0, bar => [0, 1] }; $src->{baz} = $src; my $dst = Storable::dclone($src); print Dumper($src); print Dumper($dst);
Transform the following PHP implementation into Perl, maintaining the same output and logic.
function inOrder($arr){ for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ return false; } } } return true; } function permute($items, $perms = array( )) { if (empty($items)) { if(inOrder($perms)){ return $perms; } } else { for ($i = count($items) ...
sub psort { my ($x, $d) = @_; unless ($d //= $ $x->[$_] < $x->[$_ - 1] and return for 1 .. $ return 1 } for (0 .. $d) { unshift @$x, splice @$x, $d, 1; next if $x->[$d] < $x->[$d - 1]; return 1 if p...
Write the same algorithm in Perl as shown in this PHP implementation.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
package Life; use strict; use warnings; sub meaning_of_life { return 42; } unless(caller) { print "Main: The meaning of life is " . meaning_of_life() . "\n"; }
Ensure the translated Perl code behaves exactly like the original PHP snippet.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
package Life; use strict; use warnings; sub meaning_of_life { return 42; } unless(caller) { print "Main: The meaning of life is " . meaning_of_life() . "\n"; }
Convert the following code from PHP to Perl, ensuring the logic remains intact.
<?php function printLastSundayOfAllMonth($year) { $months = array( 'January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); foreach ($months as $month) { echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month ...
use strict ; use warnings ; use DateTime ; for my $i( 1..12 ) { my $date = DateTime->last_day_of_month( year => $ARGV[ 0 ] , month => $i ) ; while ( $date->dow != 7 ) { $date = $date->subtract( days => 1 ) ; } my $ymd = $date->ymd ; print "$ymd\n" ; }
Can you help me rewrite this code in Perl instead of PHP, keeping it the same logically?
<?php function printLastSundayOfAllMonth($year) { $months = array( 'January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); foreach ($months as $month) { echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month ...
use strict ; use warnings ; use DateTime ; for my $i( 1..12 ) { my $date = DateTime->last_day_of_month( year => $ARGV[ 0 ] , month => $i ) ; while ( $date->dow != 7 ) { $date = $date->subtract( days => 1 ) ; } my $ymd = $date->ymd ; print "$ymd\n" ; }
Change the following PHP code into Perl without altering its purpose.
<?php $attributesTotal = 0; $count = 0; while($attributesTotal < 75 || $count < 2) { $attributes = []; foreach(range(0, 5) as $attribute) { $rolls = []; foreach(range(0, 3) as $roll) { $rolls[] = rand(1, 6); } sort($rolls); array_shift...
use strict; use List::Util 'sum'; my ($min_sum, $hero_attr_min, $hero_count_min) = <75 15 3>; my @attr_names = <Str Int Wis Dex Con Cha>; sub heroic { scalar grep { $_ >= $hero_attr_min } @_ } sub roll_skip_lowest { my($dice, $sides) = @_; sum( (sort map { 1 + int rand($sides) } 1..$dice)[1..$dice-1] ); } m...
Write a version of this PHP function in Perl with identical behavior.
<?php class Node { public $val; public $back = NULL; } function lis($n) { $pileTops = array(); foreach ($n as $x) { $low = 0; $high = count($pileTops)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($pileTops[$mid]->val >= $x) $...
use strict; sub lis { my @l = map [], 1 .. @_; push @{$l[0]}, +$_[0]; for my $i (1 .. @_-1) { for my $j (0 .. $i - 1) { if ($_[$j] < $_[$i] and @{$l[$i]} < @{$l[$j]} + 1) { $l[$i] = [ @{$l[$j]} ]; } } push @{$l[$i]}, $_[$i]; } my ($max...
Change the following PHP code into Perl without altering its purpose.
<?php $varname = rtrim(fgets(STDIN)); # type in "foo" on standard input $$varname = 42; echo "$foo\n"; # prints "42" ?>
print "Enter a variable name: "; $varname = <STDIN>; chomp($varname); $$varname = 42; print "$foo\n";
Port the provided PHP code into Perl while preserving the original functionality.
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
sub eval_with_x {my $code = shift; my $x = shift; my $first = eval $code; $x = shift; return eval($code) - $first;} print eval_with_x('3 * $x', 5, 10), "\n";
Transform the following PHP implementation into Perl, maintaining the same output and logic.
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
sub eval_with_x {my $code = shift; my $x = shift; my $first = eval $code; $x = shift; return eval($code) - $first;} print eval_with_x('3 * $x', 5, 10), "\n";
Write the same algorithm in Perl as shown in this PHP implementation.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
my ($a, $b) = (-5, 7); $ans = eval 'abs($a * $b)';
Transform the following PHP implementation into Perl, maintaining the same output and logic.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
my ($a, $b) = (-5, 7); $ans = eval 'abs($a * $b)';
Write a version of this PHP function in Perl with identical behavior.
function getitem($s,$depth=0) { $out = ['']; while ($s) { $c = $s[0]; if ($depth && ($c == ',' || $c == '}')) { return [$out, $s]; } if ($c == '{') { $x = getgroup(substr($s, 1), $depth + 1); if($x) { $tmp = []; ...
sub brace_expand { my $input = shift; my @stack = ([my $current = ['']]); while ($input =~ /\G ((?:[^\\{,}]++ | \\(?:.|\z))++ | . )/gx) { if ($1 eq '{') { push @stack, [$current = ['']]; } elsif ($1 eq ',' && @stack > 1) { push @{$stack[-1]}, ($current = ...
Transform the following PHP implementation into Perl, maintaining the same output and logic.
$img = imagegrabscreen(); $color = imagecolorat($im, 10, 50); imagedestroy($im);
use strict; use warnings; use GD; my $file = '/tmp/one-pixel-screen-capture.png'; system "screencapture -R 123,456,1,1 $file"; my $image = GD::Image->newFromPng($file); my $index = $image->getPixel(0,0); my($red,$green,$blue) = $image->rgb($index); print "RGB: $red, $green, $blue\n"; unlink $file;
Ensure the translated Perl code behaves exactly like the original PHP snippet.
<?php $ldap = ldap_connect($hostname, $port); $success = ldap_bind($ldap, $username, $password);
use Net::LDAP; my $ldap = Net::LDAP->new('ldap://ldap.example.com') or die $@; my $mesg = $ldap->bind( $bind_dn, password => $bind_pass );
Please provide an equivalent version of this PHP code in Perl.
<?php $client = new SoapClient("http://example.com/soap/definition.wsdl"); $result = $client->soapFunc("hello"); $result = $client->anotherSoapFunc(34234); $client = new SoapClient("http://example.com/soap/definition.wsdl"); print_r($client->__getTypes()); print_r($client->__getFunctions()); ?>
use SOAP::Lite; print SOAP::Lite -> service('http://example.com/soap/wsdl') -> soapFunc("hello"); print SOAP::Lite -> service('http://example.com/soap/wsdl') -> anotherSoapFunc(34234);
Write the same code in Perl as shown below in PHP.
$lst = new SplDoublyLinkedList(); foreach (array(1,20,64,72,48,75,96,55,42,74) as $v) $lst->push($v); foreach (strandSort($lst) as $v) echo "$v "; function strandSort(SplDoublyLinkedList $lst) { $result = new SplDoublyLinkedList(); while (!$lst->isEmpty()) { $sorted = new SplDoublyLinkedList();...
use strict; use warnings; use feature 'say'; sub merge { my ($x, $y) = @_; my @out; while (@$x and @$y) { my $t = $x->[-1] <=> $y->[-1]; if ($t == 1) { unshift @out, pop @$x } elsif ($t == -1) { unshift @out, pop @$y } else { splice @out, 0, 0, pop(@$x), pop(...
Produce a functionally identical Perl code for the snippet given in PHP.
<?php $doc = DOMDocument::loadXML('<inventory title="OmniCorp Store #45x10^3">...</inventory>'); $xpath = new DOMXPath($doc); $nodelist = $xpath->query('//item'); $result = $nodelist->item(0); $nodelist = $xpath->query('//price'); for($i = 0; $i < $nodelist->length; $i++) { print $doc->saveXML($nodelist->item($i...
use XML::XPath qw(); my $x = XML::XPath->new('<inventory ... </inventory>'); [$x->findnodes('//item[1]')->get_nodelist]->[0]; print $x->findnodes_as_string('//price'); $x->findnodes('//name')->get_nodelist;
Convert this PHP snippet to Perl and keep its semantics consistent.
<?php $conf = file_get_contents('update-conf-file.txt'); $conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf); $conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf); $conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf); if (preg_match('/^;?\s*(numberofstrawberries)/mi'...
use warnings; use strict; my $needspeeling = 0; my $seedsremoved = 1; my $numberofstrawberries = 62000; my $numberofbananas = 1024; my $favouritefruit = 'bananas'; my @out; sub config { my (@config) = <DATA>; push @config, "NUMBEROFSTRAWBERRIES $numberofstrawberries\n" unle...